ToddBeaulieu
Tue Mar 04 17:46:00 CST 2008
Jon, you ROCK!
Thanks, bud. That was exactly what I needed.
It's funny about the "envying" bit. I *am* quite excited lately about all
these new wonderful technologies I'm learning.
After getting a simple, but nonetheless cool LINQ query going in my app, and
thus avoiding the usual enumeration mess, I actually looked for someone to
share the moment with. Sadly, nobody there would have cared. :(
I will certainly need to study your message some more so I can understand it.
Thanks again!
"Jon Skeet [C# MVP]" wrote:
> Todd Beaulieu <ToddBeaulieu@discussions.microsoft.com> wrote:
> > I suspect this is super simple, but I'm just getting started with linq.
>
> I almost envy you, having the wonderful journey of discovery still
> almost entirely ahead of you. (That's not to say I've stopped learning
> about LINQ - far from it.)
>
> > I have a collection, say Orders. Under each Order I have a collection of
> > Lines.
> >
> > I want to get a distinct list of ItemNumbers for all Orders.
> >
> > Does anyone know how to do this? Is it a SelectMany()?
>
> I'm assuming we have a situation like this:
>
> public class Order
> {
> public IEnumerable<Line> Lines { get; set; }
> }
>
> public class Line
> {
> public int ItemNumber;
> public int Quantity { get; set; }
> }
>
> and you have an IEnumerable<Order> to examine.
>
> You want to end up with an IEnumerable<int> which consists of all the
> ItemNumbers of all the orders, but distinct. In other words, "all the
> items we've sold *any* of". Is that about right?
>
> The simplest way to do this is to use SelectMany(), as you've
> suggested. That's usually more easily expressed in a query expression.
> So, we'd have:
>
> var allItems = from order in orders
> from line in order.Lines
> select line.ItemNumber;
>
> var distinctItems = allItems.Distinct();
>
>
> So, allItems effectively flattens the sequence of item numbers, and
> then the second statement finds the distinct items. The query
> expression boils down to this:
>
> var allItems = orders.SelectMany (order => order.Lines,
> (order, line) => line.ItemNumber);
>
> Does that help? Let me know if I've missed the boat, and I'll have
> another go :)
>
> --
> Jon Skeet - <skeet@pobox.com>
>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
> World class .NET training in the UK:
http://iterativetraining.co.uk
>