如何使用Linq从对象列表中获取唯一的属性列表? [英] How do I use Linq to obtain a unique list of properties from a list of objects?

查看:128
本文介绍了如何使用Linq从对象列表中获取唯一的属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Linq返回一个id列表,其中id是一个属性的对象列表。我想能够做到这一点,而不循环通过每个对象,并拉出我找到的唯一ids。

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.

我有一个类型MyClass的对象列表,此类的属性之一是一个ID。

I have a list of objects of type MyClass and one of the properties of this class is an ID.

public class MyClass
{
  public int ID { get; set; }
}

我想要做的是写一个Linq查询返回一个列表的那些Ids

What I want to do is write a Linq query to return me a list of those Ids

如何使用 IList< MyClass> $ c> IEnumerable< int> of the id?

How do I do that given an IList<MyClass> such that it returns an IEnumerable<int> of the ids?

我确信必须可以在一行或两行

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.

在创建一个优雅的解决方案的任何帮助将非常赞赏!

Any help in creating an elegant solution would be much appreciated!

推荐答案

IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();

这篇关于如何使用Linq从对象列表中获取唯一的属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆