Reputation: 17701
I have list of ids like this below
List<int> ids = new List<int>();
and then i have list of lengths which is also integers like this below..
List<int> lengths = new List<int>();
now i need to insert into table using linq query with the data format like this below
ID length
1 1
1 2
1 3
2 1
2 2
2 3
for that i am doing like this
foreach (var item in ids)
{
foreach (var item in lengths)
{
}
}
With the above way i am not able insert the multiple id's in the table .. I am hoping there should be better way to do this.. Could any one please suggest any ideas on this one that would be very grateful to me..
Thanks in advance.
Upvotes: 0
Views: 771
Reputation: 81533
If you wanted to project these 2 lists to a flattened list with LINQ, you could use SelectMany
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
// projecting to an anonymous type
var results = ids.SelectMany(id => lengths.Select(length => new {id, length }));
// or projecting to a value tuple
var results = ids.SelectMany(id => lengths.Select(length => (id, length)));
Upvotes: 3
Reputation: 26926
If you really want a single loop, you can loop over the final result length and compute the indexes into each List
:
var idsCount = ids.Count;
var lengthsCount = lengths.Count;
var totalCount = idsCount * lengthsCount;
for (int j1 = 0; j1 < totalCount; ++j1) {
var id = ids[j1 / lengthsCount];
var length = lengths[j1 % lengthsCount];
new { id, length }.Dump();
// insert id,length
}
Upvotes: 0