0

Selecting from a list of lists in a lambda expression, I access the elements with ElementAt. However, it would be nicer to have the elements of my list directly as parameters for my lamda expression:

using System.Linq;
using System.Collections.Generic;

public class Program {
    public static void Main()
    {
        List<List<int>> mylist = new List<List<int>>();
        mylist.Add(new List<int>{1,2});
        mylist.Add(new List<int>{3,4});
        
        // returns a list with summed values of the input lists     
        List <int> sums = mylist.Select(x => x.ElementAt(0) +x.ElementAt(1)).ToList();

        // Can I somehow use the elements in my lists as parameters to lambda?  
        // List <int> sums = mylist.Select((x, y) => x + y).ToList();
    }
}

This is possible for tuples C# 7 tuples and lambdas

But can I do this without converting my list to Tuples?

user1981275
  • 13,002
  • 8
  • 72
  • 101

1 Answers1

0

Your first option, assuming you are genuinely using + and aren't merely using + to disguise your actual use case, is to use x.Sum():

var sums = mylist.Select(x => x.Sum());

If + is a placeholder for some other operation, you'll instead want to look at Aggregate:

var sums = mylist.Select(list => list.Aggregate((x, y) => x + y));

(Note that (x, y) => x + y is the exact lambda you give as an example in your question.)

Here's a funtioning program to demonstrate, simply uncomment the appropriate line for the technique you wish to observe:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            var mylist = new List<List<int>>()
            {
                new List<int> { 1, 2 },
                new List<int> { 3, 4 }
            };

            // Uncomment one of the following:
            // var sums = mylist.Select(x => x.Sum());
            // var sums = mylist.Select(list => list.Aggregate((x, y) => x + y));

            foreach (var sum in sums)
                Console.WriteLine(sum);

            Console.ReadKey();
        }
    }
}
Pharap
  • 3,826
  • 5
  • 37
  • 51