Get a list of distinct values in List

c# linq list distinct

363795 просмотра

5 ответа

1958 Репутация автора

In C#, say I have a class called Note with three String member variables.

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

And I have a list of type Note:

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

What would be the cleanest way to get a list of all distinct values in the Author column?

I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.

Автор: Darrel Hoffman Источник Размещён: 21.04.2012 12:31

Ответы (5)


302 плюса

63741 Репутация автора

Решение
Notes.Select(x => x.Author).Distinct();

This will return a sequence (IEnumerable<string>) of Author values -- one per unique value.

Автор: Kirk Woll Размещён: 21.04.2012 12:33

29 плюса

3373 Репутация автора

Jon Skeet has written a library called morelinq which has a DistinctBy() operator. See here for the implementation. Your code would look like

IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);

Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.

Added sample, several fields in DistinctBy:

res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();
Автор: Dan Busha Размещён: 21.04.2012 12:37

-2 плюса

37 Репутация автора

mcilist = (from mci in mcilist select mci).Distinct().ToList();
Автор: ravinderreddy Seeelam Размещён: 09.10.2013 09:26

74 плюса

3181 Репутация автора

Distinct the Note class by Author

var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());

foreach(var item in DistinctItems)
{
    //Add to other List
}
Автор: atik sarker Размещён: 23.06.2014 07:01

2 плюса

31 Репутация автора

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

Автор: Bhaskar Размещён: 23.11.2017 05:25
Вопросы из категории :
32x32