Get a list of distinct values in List

后端 未结 5 1284
孤城傲影
孤城傲影 2020-11-27 12:01

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

public class Note
{
    public string Title;
    public string Author;
    public s         


        
相关标签:
5条回答
  • 2020-11-27 12:14
    mcilist = (from mci in mcilist select mci).Distinct().ToList();
    
    0 讨论(0)
  • 2020-11-27 12:15

    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
    }
    
    0 讨论(0)
  • 2020-11-27 12:16

    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();
    
    0 讨论(0)
  • 2020-11-27 12:23
    Notes.Select(x => x.Author).Distinct();
    

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

    0 讨论(0)
  • 2020-11-27 12:25
    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.

    0 讨论(0)
提交回复
热议问题