October 17, 2008
Sometimes I Impress Even Myself

C# Problem:

You have one generic list of type<T>. Each T in turn contains two generic lists of type<A> and type<B>. A and B implement interface I. A method exists which requires a generic list of type<I>. From the parent list of type<T>, how do you feed the method its required list of <I>?

(My) Solution:

List<I> il = new List<I>();
topList.Select(x => x.ListOfA).ToList().ForEach(x => x.ForEach(y=>il.Add((I)y)));
topList.Select(x => x.ListOfB).ToList().ForEach(x => x.ForEach(y=>il.Add((I)y)));
Result r = SomeMethod(il);

Bonus:

Is there a way to implement this by re-casting the objects in listofA and listofB to I without using a ForEach() call?

Can both lists be combined into one using a single line of code instead of two?

Is it necessary to instantiate il before proceeding?

The above code actually does work. It worked on the first try, even! And I am genuinely curious about the questions. S'my site, I'll talk about what I want! :)

Posted by scott at October 17, 2008 03:06 PM

eMail this entry!
Comments

you should be able to do it in one line using .SelectMany() and .Union(). even using your above code, il.AddRange(someLinqStatement) would have been more elegant than the .ForEach()

let's see...

var il = topList.SelectMany(x => x.ListOfA.Cast()).Concat(topList.SelectMany(x => x.ListOfB.Cast()));

that should work.

dude, next time, just email me. :-)

Posted by: mrfred on October 18, 2008 02:03 AM

Ah-*HA*!!! I *knew* there had to be a way to cast & flatten the thing all at once. I just couldn't figure out how to phrase it right. All of my searches came up empty.

I all honesty, I couldn't even frame the question properly until I'd already solved it.

However, one question... why Cast()? Shouldn't it be Cast(I) or something like that? I can't see just from looking how it knows to go from type A & type B to type I.

Posted by: scott on October 18, 2008 07:24 AM

notice the comment switching to italics halfway though... it ate the Cast left-bracket I right-bracket into a style marking...

let's try again... the left bracket into left-square brackets for readability

var il = topList.SelectMany(x => x.ListOfA.Cast[I]()).Concat(topList.SelectMany(x => x.ListOfB.Cast[I]()));

Posted by: mrfred on October 18, 2008 08:11 PM
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?