Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of of objects to list of tuple without iterating

I'm trying to add an extra parameter to a list of ef objects to track processing, but I keep running into having to initialize each list item explicitly. What's the correct linq way to do this? Aside from terseness, is there any advantage to a linq syntax in this case?

List<app_subjects> subjectList = AppMySQLQueries.GetAllSubjects();
List<Tuple<app_subjects, bool>> subjectCollection = new List<Tuple<app_subjects, bool>>(subjectList.Count);

foreach (app_subjects subject in subjectList)
{
     subjectCollection.Add(Tuple.Create(subject, false));
}

I have searched the site without success.

like image 222
aldosa Avatar asked Sep 06 '13 18:09

aldosa


People also ask

How do I convert a list to a list of tuples?

A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.

How do I make a list into a list of tuples in Python?

To convert the Python list to a tuple, use the tuple() function. The tuple() is a built-in function that passes the list as an argument and returns the tuple. The list elements will not change when it converts into a tuple.


1 Answers

You just want to use a projection here ( Select ) which applies the transformation in your lambda expression to each element in the source collection.

List<Tuple<app_subjects, bool>> tuples = subjectList.Select(x => new Tuple<app_subjects, bool>(x, false)).ToList();

The ToList() call is not entirely necessary, if you removed it then the method will return an IEnumerable<Tuple<app_subjects, bool>>. If you're just going to iterate the collection of tuples afterwards the ToList call should be removed as it forces execution (enumerates the IEnumberable) and then your next operation (the foreach) would do the same, making the code perform worse.

like image 130
evanmcdonnal Avatar answered Sep 30 '22 11:09

evanmcdonnal