如何在LINQ的添加两个列表,以便addedList [X] =那么listOne [X] + listTwo [X] [英] How do I add two lists in Linq so addedList[x] = listOne[x] + listTwo[x]?
本文介绍了如何在LINQ的添加两个列表,以便addedList [X] =那么listOne [X] + listTwo [X]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想补充一个数字类型,这样的两个列表 addedList [X] =那么listOne [X] + listTwo [X]
列表的输出必须是Generic.IEnumerable我可以在将来LINQ查询使用。
当我能够用低于code做到这一点,我不禁觉得必须有一个更好的办法。任何想法?
名单,其中,INT> firstList =新列表与所述; INT>(新INT [] {1,3,4,2,5,7,2,5,7,8,9,0});
名单< INT> secondList =新列表与所述; INT>(新INT [] {4,6,8,3,1,5,9,3,0});
INT findex = 0;
ILookup< INT,INT> flookup = firstList.ToLookup(F =>
{
INT I = findex;
findex ++;
返回我;
},p值=> p)的;
VAR listsAdded =从GRP在flookup
选择grp.First()+ secondList.ElementAtOrDefault(grp.Key);
的foreach(诠释我在listsAdded)
Console.WriteLine(ⅰ);
解决方案
VAR的结果=
从我在
Enumerable.Range(0,Math.Max(firstList.Count,secondList.Count))
选择firstList.ElementAtOrDefault(我)+ secondList.ElementAtOrDefault(我);
I want to add two lists of a numeric type such that addedList[x] = listOne[x] + listTwo[x]
The output of the list needs to be a Generic.IEnumerable that I can use in future linq queries.
While I was able to do it using the code below, I can't help but feel like there must be a better way. Any ideas?
List<int> firstList = new List<int>(new int[] { 1, 3, 4, 2, 5, 7, 2, 5, 7, 8, 9, 0 });
List<int> secondList = new List<int>(new int[] { 4, 6, 8, 3, 1, 5, 9, 3, 0 });
int findex = 0;
ILookup<int, int> flookup = firstList.ToLookup(f =>
{
int i = findex;
findex++;
return i;
}, p => p);
var listsAdded = from grp in flookup
select grp.First() + secondList.ElementAtOrDefault(grp.Key);
foreach (int i in listsAdded)
Console.WriteLine(i);
解决方案
var result =
from i in
Enumerable.Range(0, Math.Max(firstList.Count, secondList.Count))
select firstList.ElementAtOrDefault(i) + secondList.ElementAtOrDefault(i);
这篇关于如何在LINQ的添加两个列表,以便addedList [X] =那么listOne [X] + listTwo [X]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文