我应该如何从List& T& gt;中提取不同值的集合自定义对象? [英] How should I extract a collection of distinct values from a List<T> of custom objects?

查看:53
本文介绍了我应该如何从List& T& gt;中提取不同值的集合自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表-假设它们是订单.

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 SalesmanIds 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&amp; T&amp; gt;中提取不同值的集合自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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