简体   繁体   中英

How to group by 2 items of a list into another list

As for this example:

Get a list of distinct values in List

This demonstrates how to get a distinct list based on 1 item.

How do you get a distinct list of 2 things. Say Author and title.

public class Note
{
    public string Title;
    public string Author;
    public string Text;
}

List<Note> Notes = new List<Note>();

The answer for one is:

Notes.Select(x => x.Author).Distinct();

As jdweng suggested in the comments you can do:

Notes.Select(x => new string[] {x.Title, x.Author}).Distinct();

which will return a IEnumerable<string[]> .

Another option is to create a class to select into:

public class NoteSummary()
{
    public string Title { get; set; }
    public string Author { get; set; }

    public NoteSummary(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

Then the linq becomes:

Notes.Select(x => new NoteSummary(x.Title, x.Author)).Distinct();

which returns IEnumerable<NoteSummary> .

If you want to return a grouped collection of the original Note class/entity you can use GroupBy :

Notes
  .GroupBy(g => new { g.Title, g.Author })  // group by fields
  .Select(g => g.First());                  // select first group

which returns IEnumerable<Note> .

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