2

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();
KeithL
  • 5,348
  • 3
  • 19
  • 25

1 Answers1

1

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>.

haldo
  • 14,512
  • 5
  • 46
  • 52
  • I think this is going to answer my follow on question from https://stackoverflow.com/questions/55423245/after-getting-distinct-list-using-the-results-in-a-query – KeithL Mar 29 '19 at 18:09