Reputation: 23
I have two list of Object in C#:
[{roomID = 1}, {roomID = 2}]
[{companyID = x}, {companyID = y}, {companyID = z}]
and I wanna have the output like this:
combList = [{roomID = 1, companyID = x}, {roomID = 1, companyID = y}, {roomID = 1, companyID = z}, {roomID = 2, companyID = x}, ...]
I have used foreach to create the combList but the problem is that the roomList and companyList are too large and it takes lots of time to create the combList is there any other solution?
Upvotes: 0
Views: 60
Reputation: 174425
What you're after here is known as the cartesian product of two lists - and as you've found, it's not feasible to generate all possible values and materialize/store them up front when the input sizes start growing.
Luckily, all the LINQ
methods tend to produce enumerables - lazily generated collections - instead of materialized collections, so you can start working on the different combinations instead of waiting for the whole range to be generated:
var roomList = Enumerable.Range(1, 3).Select(i => new {roomID = i});
var companyList = "x y z".Split().Select(s => new {companyID = s});
var combEnumerables = roomList.SelectMany(room => companyList, (r, c) => new {roomID = r.roomID, companyID = c.companyID});
foreach(var combo in combEnumerables)
{
Console.WriteLine($"We could assign room {combo.roomID} to company {combo.companyID}");
}
Upvotes: 2