How do I add two lists in Linq so addedList[x] = listOne[x] + listTwo[x]?

前端 未结 4 1685
我寻月下人不归
我寻月下人不归 2021-01-05 02:43

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 i

相关标签:
4条回答
  • 2021-01-05 03:23

    What you're looking for is a Zip method. This method allows you to combine to lists of equal length into a single list by applying a projection.

    For example

    var sumList = firstList.Zip(secondList, (x,y) => x + y).ToList();
    

    This method was added to the BCL in CLR 4.0 (Reference). It's fairly straight forward to implement though and many versions are available online that can be copied into a 2.0 or 3.5 application.

    0 讨论(0)
  • 2021-01-05 03:31
    var result = 
       from i in 
            Enumerable.Range(0, Math.Max(firstList.Count, secondList.Count))
       select firstList.ElementAtOrDefault(i) + secondList.ElementAtOrDefault(i);
    
    0 讨论(0)
  • 2021-01-05 03:31

    It sounds like you want a function like this:

    public static IEnumerable<int> SumIntLists( 
        this IEnumerable<int> first, 
        IEnumerable<int> second) 
    {
        using(var enumeratorA = first.GetEnumerator()) 
        using(var enumeratorB = second.GetEnumerator()) 
        { 
            while (enumeratorA.MoveNext()) 
            {
                if (enumeratorB.MoveNext())
                    yield return enumeratorA.Current + enumeratorB.Current;
                else
                    yield return enumeratorA.Current;
            }
            // should it continue iterating the second list?
            while (enumeratorB.MoveNext())
                yield return enumeratorB.Current;
        } 
    } 
    
    0 讨论(0)
  • 2021-01-05 03:35
    var res = list.Concat(list1); 
    

    concatenates two lists, including eventual duplicates.

    var res = list.Union(list1);
    

    concatenates two lists, providing a result without duplicates.

    0 讨论(0)
提交回复
热议问题