我应该如何从List& 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
的 Distinct
列表.做这个的最好方式是什么?我不认为它是手动循环的...是吗?
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?
更新感谢您的回复.我想到了一个额外的要求(在Jon Skeets回答后概述),并这样编码:
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:这一次又一次-像我这样的新手可能会找到此的答案链接的问题也是有用的.
UPDATE #2: This one ran and ran - newbies like me might find answers to this linked question useful too.
推荐答案
如果只需要获取SalesmanId,就很容易:
If you only need to get the SalesmanIds, it's easy:
var salesmanIds = orders.Select(x => x.SalesmanId)
.Distinct();
如果需要将其作为 List< T>
,请调用 ToList()
.
Call ToList()
if you need it as a List<T>
.
您需要为 System.Linq
使用using指令.
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();
这篇关于我应该如何从List& T& gt;中提取不同值的集合自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!