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

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

问题描述

我正在尝试使用 LINQ 返回一个 id 列表,给定一个对象列表,其中 id 是一个属性.我希望能够在不遍历每个对象并提取我找到的唯一 ID 的情况下执行此操作.

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 查询来返回这些 ID 的列表.

I want to write a LINQ query to return me a list of those Ids.

如果给定一个 IList 使其返回 ID 的 IEnumerable,我该怎么做?

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

我确信必须可以使用 LINQ 在一行或两行中完成,而不是遍历 MyClass 列表中的每个项目并将唯一值添加到列表中.

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.

推荐答案

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

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

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