Linq 范围问题 +减少重复代码

发布于 2024-10-20 10:25:05 字数 5213 浏览 1 评论 0原文

如果参数为 -1,则需要运行不同的查询以确定是否指定了 ID...我该如何执行此操作?我尝试过初始化 var q;在 If 块之外但运气不好!

 // Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
    IEnumerable<tblBlogEntry> q;
    if (EntryID == -1)
    {
        q = (
            from Blog in db.tblBlogEntries
            orderby Blog.date descending
            select new
            {
                Blog.ID,
                Blog.title,
                Blog.entry,
                Blog.date,
                Blog.userID,
                Comments = (
                    from BlogComments in db.tblBlogComments 
                    where BlogComments.blogID == Blog.ID 
                    select BlogComments).Count(),
                Username = (
                    from Users in db.yaf_Users 
                    where Users.UserID == Blog.userID 
                    select new { Users.DisplayName })
            }).FirstOrDefault();
    }
    else
    {
        q = (
            from Blog in db.tblBlogEntries
            where Blog.ID == EntryID
            select new
            {
                Blog.ID,
                Blog.title,
                Blog.entry,
                Blog.date,
                Blog.userID,
                Comments = (
                    from BlogComments in db.tblBlogComments 
                    where BlogComments.blogID == Blog.ID 
                    select BlogComments).Count(),
                Username = (
                    from Users in db.yaf_Users 
                    where Users.UserID == Blog.userID 
                    select new { Users.DisplayName })
            }).SingleOrDefault();
    }
    if (q == null)
    {
        this.Loaded = false;
    }
    else
    {
        this.ID = q.ID;
        this.Title = q.title;
        this.Entry = q.entry;
        this.Date = (DateTime)q.date;
        this.UserID = (int)q.userID;
        this.Loaded = true;
        this.AuthorUsername = q.Username;
    }       
}

我的主要目标是减少重复代码

编辑

根据我现在得到的一些答案:

// Blog data model
public class EntryModel
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Entry { get; set; }
    public DateTime Date { get; set; }
    public int UserID { get; set; }
    public string Username { get; set; }
    public int Comments { get; set; }
}

// A single blog entry
public class BlogEntry
{
    public bool Loaded;     // Did this entry load OK?
    private DataClassesDataContext db = new DataClassesDataContext();
    public EntryModel ThisEntry = new EntryModel();

    // Initialisers
    public BlogEntry(int EntryID)
    {
        this.LoadEntryByID(EntryID);
    }
    public BlogEntry()
    {
        this.LoadLatest();
    }
    public void LoadLatest()
    {
        this.LoadEntryByID(-1);
    }      

    // Loads by Entry ID, or if -1, by latest entry
    private void LoadEntryByID(int EntryID)
    {
        EntryModel q = null;
        if (EntryID == -1)
        {
            q = (from Blog in db.tblBlogEntries
                 orderby Blog.date descending
                 select new EntryModel
                 {
                     Title = Blog.title,
                     ID = Blog.ID,
                     Entry = Blog.entry,
                     Date = (DateTime)Blog.date,
                     UserID = (int)Blog.userID,
                     Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                     Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString()
                 }
                 ).FirstOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select new EntryModel
                     {
                         Title = Blog.title,
                         ID = Blog.ID,
                         Entry = Blog.entry,
                         Date = (DateTime)Blog.date,
                         UserID = (int)Blog.userID,
                         Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                         Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString()
                     }).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {            
            this.ThisEntry.ID = q.ID;
            this.ThisEntry.Title = q.Title;
            this.ThisEntry.Entry = q.Entry;
            this.ThisEntry.Date = q.Date;
            this.ThisEntry.UserID = q.UserID;
            this.Loaded = true;
            this.ThisEntry.Username = q.Username;
            this.ThisEntry.Comments = q.Comments;
        }       
    }
}

这有效,但在 VS 中抛出大量蓝色波浪线,并

this.ThisEntry.Username = q.Username;

在 HTML 中输出到:

{ DisplayName = 汤姆 }

不只是我想要的“Tom”!

If the parameter is -1, it needs to run a different query as to if an ID was specified... how do I do this? I've tried initialising var q; outside the If block but no luck!

 // Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
    IEnumerable<tblBlogEntry> q;
    if (EntryID == -1)
    {
        q = (
            from Blog in db.tblBlogEntries
            orderby Blog.date descending
            select new
            {
                Blog.ID,
                Blog.title,
                Blog.entry,
                Blog.date,
                Blog.userID,
                Comments = (
                    from BlogComments in db.tblBlogComments 
                    where BlogComments.blogID == Blog.ID 
                    select BlogComments).Count(),
                Username = (
                    from Users in db.yaf_Users 
                    where Users.UserID == Blog.userID 
                    select new { Users.DisplayName })
            }).FirstOrDefault();
    }
    else
    {
        q = (
            from Blog in db.tblBlogEntries
            where Blog.ID == EntryID
            select new
            {
                Blog.ID,
                Blog.title,
                Blog.entry,
                Blog.date,
                Blog.userID,
                Comments = (
                    from BlogComments in db.tblBlogComments 
                    where BlogComments.blogID == Blog.ID 
                    select BlogComments).Count(),
                Username = (
                    from Users in db.yaf_Users 
                    where Users.UserID == Blog.userID 
                    select new { Users.DisplayName })
            }).SingleOrDefault();
    }
    if (q == null)
    {
        this.Loaded = false;
    }
    else
    {
        this.ID = q.ID;
        this.Title = q.title;
        this.Entry = q.entry;
        this.Date = (DateTime)q.date;
        this.UserID = (int)q.userID;
        this.Loaded = true;
        this.AuthorUsername = q.Username;
    }       
}

My main aim is to reduce repeating code

Edit

As per some answers I've now got:

// Blog data model
public class EntryModel
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Entry { get; set; }
    public DateTime Date { get; set; }
    public int UserID { get; set; }
    public string Username { get; set; }
    public int Comments { get; set; }
}

// A single blog entry
public class BlogEntry
{
    public bool Loaded;     // Did this entry load OK?
    private DataClassesDataContext db = new DataClassesDataContext();
    public EntryModel ThisEntry = new EntryModel();

    // Initialisers
    public BlogEntry(int EntryID)
    {
        this.LoadEntryByID(EntryID);
    }
    public BlogEntry()
    {
        this.LoadLatest();
    }
    public void LoadLatest()
    {
        this.LoadEntryByID(-1);
    }      

    // Loads by Entry ID, or if -1, by latest entry
    private void LoadEntryByID(int EntryID)
    {
        EntryModel q = null;
        if (EntryID == -1)
        {
            q = (from Blog in db.tblBlogEntries
                 orderby Blog.date descending
                 select new EntryModel
                 {
                     Title = Blog.title,
                     ID = Blog.ID,
                     Entry = Blog.entry,
                     Date = (DateTime)Blog.date,
                     UserID = (int)Blog.userID,
                     Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                     Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString()
                 }
                 ).FirstOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select new EntryModel
                     {
                         Title = Blog.title,
                         ID = Blog.ID,
                         Entry = Blog.entry,
                         Date = (DateTime)Blog.date,
                         UserID = (int)Blog.userID,
                         Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                         Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString()
                     }).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {            
            this.ThisEntry.ID = q.ID;
            this.ThisEntry.Title = q.Title;
            this.ThisEntry.Entry = q.Entry;
            this.ThisEntry.Date = q.Date;
            this.ThisEntry.UserID = q.UserID;
            this.Loaded = true;
            this.ThisEntry.Username = q.Username;
            this.ThisEntry.Comments = q.Comments;
        }       
    }
}

This works, but throws a lot of blue squiggly lines in VS, and

this.ThisEntry.Username = q.Username;

Outputs in HTML to:

{ DisplayName = Tom }

Not just 'Tom' as I want it to!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

以酷 2024-10-27 10:25:05
tblBlogEntry myBlog;
if ( EntryID != -1 ) 
{
  myBlog = db.tblBlogEntries
             .SingleOrDefault( blog => blog.ID == EntryID );
}
else 
{
  myBlog = db.tblBlogEntries
             .OrderByDescending( blog => blog.date ).FirstOrDefault();
}

this.Loaded = myBlog != null;

if ( this.Loaded )
{
  this.ThisEntry = new EntryModel
  {
    ID = myBlog.ID,
    Title = myBlog.title,
    Entry = myBlog.entry,
    Date = ( DateTime )myBlog.date,
    UserID = ( int )myBlog.userID,
    Username = db.yaf_Users
                 .Single( user => user.UserID == myBlog.userID ).DisplayName,
    Comments = db.tblBlogComments
                 .Where( comment => comment.blogID == myBlog.ID ).Count()
  }
} 
tblBlogEntry myBlog;
if ( EntryID != -1 ) 
{
  myBlog = db.tblBlogEntries
             .SingleOrDefault( blog => blog.ID == EntryID );
}
else 
{
  myBlog = db.tblBlogEntries
             .OrderByDescending( blog => blog.date ).FirstOrDefault();
}

this.Loaded = myBlog != null;

if ( this.Loaded )
{
  this.ThisEntry = new EntryModel
  {
    ID = myBlog.ID,
    Title = myBlog.title,
    Entry = myBlog.entry,
    Date = ( DateTime )myBlog.date,
    UserID = ( int )myBlog.userID,
    Username = db.yaf_Users
                 .Single( user => user.UserID == myBlog.userID ).DisplayName,
    Comments = db.tblBlogComments
                 .Where( comment => comment.blogID == myBlog.ID ).Count()
  }
} 
昨迟人 2024-10-27 10:25:05

尝试

/ Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
    dynamic q = null;
    if (EntryID == -1)
    {
        q = (from Blog in db.tblBlogEntries
             orderby Blog.date descending
             select new
             {
                 Blog.ID,
                 Blog.title,
                 Blog.entry,
                 Blog.date,
                 Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                 Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault()
             }).FirstOrDefault();
    }
    else
    {
        q = (from Blog in db.tblBlogEntries
                 where Blog.ID == EntryID
                 select new
                 {
                     Blog.ID,
                     Blog.title,
                     Blog.entry,
                     Blog.date,
                     Blog.userID,
                     Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                     Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault()
                 }).SingleOrDefault();
    }
    if (q == null)
    {
        this.Loaded = false;
    }
    else
    {
        this.ID = q.ID;
        this.Title = q.title;
        this.Entry = q.entry;
        this.Date = (DateTime)q.date;
        this.UserID = (int)q.userID;
        this.Loaded = true;
        this.AuthorUsername = q.Username.DisplayName;
    }       
}

}

Try

/ Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
    dynamic q = null;
    if (EntryID == -1)
    {
        q = (from Blog in db.tblBlogEntries
             orderby Blog.date descending
             select new
             {
                 Blog.ID,
                 Blog.title,
                 Blog.entry,
                 Blog.date,
                 Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                 Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault()
             }).FirstOrDefault();
    }
    else
    {
        q = (from Blog in db.tblBlogEntries
                 where Blog.ID == EntryID
                 select new
                 {
                     Blog.ID,
                     Blog.title,
                     Blog.entry,
                     Blog.date,
                     Blog.userID,
                     Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(),
                     Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault()
                 }).SingleOrDefault();
    }
    if (q == null)
    {
        this.Loaded = false;
    }
    else
    {
        this.ID = q.ID;
        this.Title = q.title;
        this.Entry = q.entry;
        this.Date = (DateTime)q.date;
        this.UserID = (int)q.userID;
        this.Loaded = true;
        this.AuthorUsername = q.Username.DisplayName;
    }       
}

}

漫漫岁月 2024-10-27 10:25:05

您的代码有两个问题。首先,由于您只选择一个对象,因此不应将 q 声明为 IEnumerable。如果您选择了一个范围,则可以这样做。

其次,由于您将获得单个 tblBlogEntry 对象,因此您应该这样声明 Q,但是您不应该使用 NEW 选择该对象,因为这将使其成为匿名对象,并且您将获得 "CS0029 :无法将类型“AnonymousType#1”隐式转换为“tblBlogEntry””错误,您只需将其选择为 tblBlogEntry。但是,如果您不想在查询中引入整个对象,或者需要添加更多 tblBlogEntry 上没有的字段,则应该创建一个仅包含您需要的属性的新类,然后您可以创建一个新的类该类的实例:

引入整个对象及其ALL字段:

   // Loads by Entry ID, or if -1, by latest entry
    private void LoadEntryByID(int EntryID)
    {
        tblBlogEntry q;
        if (EntryID == -1)
        {
            q = (from Blog in db.tblBlogEntries
                 orderby Blog.date descending
                 select Blog).SingleOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select Blog).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {
            this.ID = q.ID;
            this.Title = q.title;
            this.Entry = q.entry;
            this.Date = (DateTime)q.date;
            this.UserID = (int)q.userID;
            this.Loaded = true;
            this.AuthorUsername = q.Username;
        }       
    }
}

仅引入一些特定字段,或引入该对象没有的字段:

public class EntryModel
{
   public int ID {get;set;}
   public string Title {get;set;}
   public string Entry{get;set;}
   public DateTime Date {get;set;}
   public int UserID {get;set;}
   public List<Comment> Comments {get;set;}
}
// Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
   EntryModel q;
   if (EntryID == -1)
   {
       q = (from Blog in db.tblBlogEntries
       orderby Blog.date descending
       select  select new EntryModel()
       {
           ID=Blog.ID,
           Title=Blog.title,
           Entry=Blog.entry,
                 Date=Blog.date,
                 UserId=Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where     BlogComments.blogID == Blog.ID select BlogComments).Count()
             }).SingleOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select select new EntryModel()
             {
                 ID=Blog.ID,
                 Title=Blog.title,
                 Entry=Blog.entry,
                 Date=Blog.date,
                 UserId=Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where     BlogComments.blogID == Blog.ID select BlogComments).Count()
             }).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {
            this.ID = q.ID;
            this.Title = q.title;
            this.Entry = q.entry;
            this.Date = (DateTime)q.date;
            this.UserID = (int)q.userID;
            this.Loaded = true;
            this.AuthorUsername = q.Username;
        }       
    }
}

There are two issues with your your code the way t is. First, since you are only selecting ONE object, you shouldn't declare q as an IEnumerable. You could do that if you selected a range.

Second, since you are going to get a single tblBlogEntry object, you should declare Q as such, but then you should not select the object with a NEW, because this will make it an anonymous object and you will get the "CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'tblBlogEntry'" error you need to just select it as a tblBlogEntry. If however, you do not want to bring the whole object with the query, or need to add more fields that you dont have on tblBlogEntry, you should create a new class that has only the attributes that you need and then you can create a new instance of that class:

Bringing the whole object with ALL its fields:

   // Loads by Entry ID, or if -1, by latest entry
    private void LoadEntryByID(int EntryID)
    {
        tblBlogEntry q;
        if (EntryID == -1)
        {
            q = (from Blog in db.tblBlogEntries
                 orderby Blog.date descending
                 select Blog).SingleOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select Blog).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {
            this.ID = q.ID;
            this.Title = q.title;
            this.Entry = q.entry;
            this.Date = (DateTime)q.date;
            this.UserID = (int)q.userID;
            this.Loaded = true;
            this.AuthorUsername = q.Username;
        }       
    }
}

Bringing the just some specific fields, or with fields that the object doesnt have:

public class EntryModel
{
   public int ID {get;set;}
   public string Title {get;set;}
   public string Entry{get;set;}
   public DateTime Date {get;set;}
   public int UserID {get;set;}
   public List<Comment> Comments {get;set;}
}
// Loads by Entry ID, or if -1, by latest entry
private void LoadEntryByID(int EntryID)
{
   EntryModel q;
   if (EntryID == -1)
   {
       q = (from Blog in db.tblBlogEntries
       orderby Blog.date descending
       select  select new EntryModel()
       {
           ID=Blog.ID,
           Title=Blog.title,
           Entry=Blog.entry,
                 Date=Blog.date,
                 UserId=Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where     BlogComments.blogID == Blog.ID select BlogComments).Count()
             }).SingleOrDefault();
        }
        else
        {
            q = (from Blog in db.tblBlogEntries
                     where Blog.ID == EntryID
                     select select new EntryModel()
             {
                 ID=Blog.ID,
                 Title=Blog.title,
                 Entry=Blog.entry,
                 Date=Blog.date,
                 UserId=Blog.userID,
                 Comments = (from BlogComments in db.tblBlogComments where     BlogComments.blogID == Blog.ID select BlogComments).Count()
             }).SingleOrDefault();
        }
        if (q == null)
        {
            this.Loaded = false;
        }
        else
        {
            this.ID = q.ID;
            this.Title = q.title;
            this.Entry = q.entry;
            this.Date = (DateTime)q.date;
            this.UserID = (int)q.userID;
            this.Loaded = true;
            this.AuthorUsername = q.Username;
        }       
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文