C# 获取 List 中不同值的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10255121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:03:46  来源:igfitidea点击:

Get a list of distinct values in List

c#linqlistdistinct

提问by Darrel Hoffman

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

在 C# 中,假设我有一个名为 Note 的类,其中包含三个 String 成员变量。

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?

在 Author 列中获取所有不同值的列表的最简洁方法是什么?

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.

我可以遍历列表并将所有不重复的值添加到另一个字符串列表中,但这看起来很脏而且效率低下。我有一种感觉,有一些神奇的 Linq 结构可以在一行中做到这一点,但我一直想不出任何东西。

采纳答案by Kirk Woll

Notes.Select(x => x.Author).Distinct();

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

这将返回一个值序列 ( IEnumerable<string>) Author—— 每个唯一值一个。

回答by Dan Busha

Jon Skeet has written a library called morelinqwhich has a DistinctBy()operator. See herefor the implementation. Your code would look like

Jon Skeet 编写了一个名为morelinq的库,它有一个DistinctBy()运算符。见这里的实现。你的代码看起来像

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:

添加了示例,DistinctBy 中的几个字段:

res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();

回答by ravinderreddy Seeelam

mcilist = (from mci in mcilist select mci).Distinct().ToList();

回答by atik sarker

Distinct the Note class by Author

按作者区分 Note 类

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

foreach(var item in DistinctItems)
{
    //Add to other List
}

回答by Bhaskar

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.

通过上面的逻辑,我们可以得到唯一的Courses。