Reputation: 5594
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();
Upvotes: 2
Views: 702
Reputation: 16711
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>
.
Upvotes: 1