Home > Uncategorized > Linq – Multiple sources

Linq – Multiple sources

MSDN has a linq sample that shows how to work with multiple sources. This also works with nested collections. Assuming class A is defined as:

class A

{

    public A() { Collection = new List<string>(); }

    public int Id { get; set; }

    public List<string> Collection { get; set; }

}

 

and a collection of A:s,

var a1 = new A { Id = 1, Collection = { “B11”, “B12”, “B13” } };

var a2 = new A { Id = 2, Collection = { “B21”, “B22”, “B23” } };

var a3 = new A { Id = 3, Collection = { “B31”, “B32”, “B33” } };

var list = new List<A> { a1, a2, a3 };

 

we can do the following:

var result =

    from a in list

    let id = a.Id

    from b in a.Collection

    select Tuple.Create(id, b);

 

foreach (var tuple in result)

{

    Console.WriteLine(“{0}, {1}”, tuple.Item1, tuple.Item2);

}

 

which will output:

1, B11
1, B12
1, B13
2, B21
2, B22
2, B23
3, B31
3, B32
3, B33

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: