我应该如何提取一个列表&LT不同值的集合; T&GT;自定义对象? [英] How should I extract a collection of distinct values from a List<T> of custom objects?
问题描述
我已经有了对象的列表 - 让我们说他们是订单
I've got a List of objects - let's say they're Orders.
订单结果的OrderID结果
日期结果
SalesmanId结果
...
我想从这个名单中提取鲜明
SalesmanId
列表。什么是做到这一点的最好方法是什么?我不认为它的循环,通过手工......是吗?
I want to extract a Distinct
list of SalesmanId
s from this list. What is the best way to do this? I don't suppose its looping through manually ... is it?
更新
感谢您的答复。我想到了一个额外的要求(乔恩长柄水杓答案后所述)和codeD这样的:
UPDATE Thanks for your responses. I've thought of an extra requirement (outlined after Jon Skeets answer) and coded it like this:
var salesusers = from s in lstOrders
group s by new { s.SalesUserId,s.Username}
into g
select new { UserName = g.Key.Username, UserId = g.Key.SalesUserId };
它的工作原理,但我不知道这是看问题的正确排序或如果我的方式没谱?
It works, but I'm not sure if this is the right sort of approach or if I'm way off the mark?
感谢。
更新#2:
这其中跑啊跑 - 像我这样的新手可能会发现回答这个<一个href=\"http://stackoverflow.com/questions/6276974/working-with-lists-anonymous-types-and-suchlike/6277153#6277153\">linked问题有用的。
推荐答案
如果你只需要获得SalesmanIds,很容易:
If you only need to get the SalesmanIds, it's easy:
var salesmanIds = orders.Select(x => x.SalesmanId)
.Distinct();
呼叫了ToList()
如果你需要它作为一个列表&LT; T&GT;
Call ToList()
if you need it as a List<T>
.
您需要一个using指令 System.Linq的
。
You need a using directive for System.Linq
.
编辑:好的,得到的名称和ID,你可以使用:
Okay, to get both the name and ID, you can use:
var salesmanIds = orders.Select(x => new { x.SalesmanId, x.UserName })
.Distinct();
这篇关于我应该如何提取一个列表&LT不同值的集合; T&GT;自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!