简体   繁体   中英

GroupBy using Linq with related Entity in C#

I need to group a list of questions by speaker using Linq:

public partial class Question
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime Date { get; set; }

    public string Description { get; set; }

    [ForeignKey("Speaker")]
    public int Speaker_Id { get; set; }
    public virtual Speaker Speaker { get; set; }
}

public partial class Speaker
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }

    public string Title { get; set; }
}

I need to create a list of Questions Grouped By Speaker:

   Question.Date  | Speaker.Name | Question.Description

I get here but it's not working:

db.Questions.Select(c => new
            {
               c.Date,
               c.Description,
               c.Speaker.Id
            })
            .ToList()
            .GroupBy(c => new { c.Id, c.Date, c.Description })
            .Select(g => new Question
            {
                Date = g.Key.Date,
                Speaker = db.Spkeakers.Where(o => o.Id == g.Key.Id).FirstOrDefault(),
                Description = g.Key.Description
            })
            .ToList());

It's sorting by Date and not grouping by Speaker.

You're including Date (a DateTime type) in your group by clause. There's a good chance that each of your rows has a different date. If that property is true for your data, then grouping by date is essentially grouping by a unique identifier. Instead, maybe try to group by a less granular date by grouping by day, month, year, etc. Also, you could just group by speakerId and only order by date.

To order by speaker and date do this:

  var result =  db.Questions
                    .OrderBy(t => t.Speaker_Id)
                    .ThenBy(t => t.Date);

This is how you group by speakers and give a count:

  var result =  db.Questions
                    .GroupBy(t => t.Speaker_Id)
                    .Select(g => new { Speaker_Id = g.Key, count = g.Count() });

This is how you show this table ordered by date

  var result = db.Questions
                   .OrderBy(t => t.Date)
                   .Select(item => new { Date = item.Date, Name = item.Speaker.Name, D = item.Description });

Note, if you want a list of Questions as your result then the last select is not needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM