[英]Get a list of distinct values in List
在 C# 中,假設我有一個名為Note
的類,其中包含三個字符串成員變量。
public class Note
{
public string Title;
public string Author;
public string Text;
}
我有一個Note
類型的列表:
List<Note> Notes = new List<Note>();
在 Author 列中獲取所有不同值的列表的最簡潔方法是什么?
我可以遍歷列表並將所有不重復的值添加到另一個字符串列表中,但這看起來很臟而且效率低下。 我有一種感覺,有一些神奇的 Linq 結構可以在一行中做到這一點,但我一直想不出任何東西。
Notes.Select(x => x.Author).Distinct();
這將返回Author
值的序列( IEnumerable<string>
)——每個唯一值一個。
按作者區分 Note 類
var DistinctItems = Notes.GroupBy(x => x.Author).Select(y => y.First());
foreach(var item in DistinctItems)
{
//Add to other List
}
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();
通過上面的邏輯,我們可以得到唯一的Course
。
mcilist = (from mci in mcilist select mci).Distinct().ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.