list 如何使用 Linq 从对象列表中获取唯一的属性列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/568347/
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
How do I use Linq to obtain a unique list of properties from a list of objects?
提问by mezoid
I'm trying to use Linq to return a list of ids given a list of objects where the id is a property. I'd like to be able to do this without looping through each object and pulling out the unique ids that I find.
我正在尝试使用 Linq 返回一个 id 列表,给定一个对象列表,其中 id 是一个属性。我希望能够在不遍历每个对象并提取我找到的唯一 ID 的情况下执行此操作。
I have a list of objects of type MyClass and one of the properties of this class is an ID.
我有一个 MyClass 类型的对象列表,这个类的属性之一是一个 ID。
public class MyClass
{
public int ID { get; set; }
}
What I want to do is write a Linq query to return me a list of those Ids
我想要做的是编写一个 Linq 查询来返回这些 Id 的列表
How do I do that given an IList<MyClass>
such that it returns an IEnumerable<int>
of the ids?
IList<MyClass>
如果它返回一个IEnumerable<int>
id ,我该怎么做?
I'm sure it must be possible to do it in one or two lines using Linq rather than looping through each item in the MyClass list and adding the unique values into a list.
我确信必须可以使用 Linq 在一两行中完成它,而不是遍历 MyClass 列表中的每个项目并将唯一值添加到列表中。
Any help in creating an elegant solution would be much appreciated!
任何帮助创建优雅的解决方案将不胜感激!
回答by Marc Gravell
IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
回答by CMS
回答by Dana
Using straight Linq, with the Distinct()
extension:
使用直接的Linq,Distinct()
扩展名:
var idList = (from x in yourList select x.ID).Distinct();
回答by Black Eagle
int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
var nonRepeats = (from n in numbers select n).Distinct();
foreach (var d in nonRepeats)
{
Response.Write(d);
}
OUTPUT
输出
1234567890
1234567890
回答by Pergin Sheni
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
在使用 Distinct 时,我们也必须转换为 IEnumerable。如果list是model手段,需要这样写代码
IEnumerable<T> ids = list.Select(x => x).Distinct();