I've got a List of objects - let's say they're Orders.
Order
OrderID
Date
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?
UPDATE Thanks for your responses. I've thought o开发者_如何转开发f 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?
Thanks.
UPDATE #2: This one ran and ran - newbies like me might find answers to this linked question useful too.
If you only need to get the SalesmanIds, it's easy:
var salesmanIds = orders.Select(x => x.SalesmanId)
.Distinct();
Call ToList()
if you need it as a List<T>
.
You need a using directive for System.Linq
.
EDIT: Okay, to get both the name and ID, you can use:
var salesmanIds = orders.Select(x => new { x.SalesmanId, x.UserName })
.Distinct();
I'd prefer this way:
Implement the IEqualityComparer<T>
interface for Order (just so you can properly compare them.
Then just do:
IEnumerable<Order> myDistinctOrders = oredersList.Distinct();
精彩评论