aldosa
aldosa

Reputation: 357

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.

Upvotes: 8

Views: 23996

Answers (4)

evanmcdonnal
evanmcdonnal

Reputation: 48154

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 IEnumerable) and then your next operation (the foreach) would do the same, making the code perform worse.

Upvotes: 19

clamchoda
clamchoda

Reputation: 4991

With C# 10.0 (.NET 6.0) this is even easier and cleaner. Along with named tuples we can also declare a tuple by simply putting the values in round brackets.

List<(string NamedProperty1, int NamedProperty2)> _tuples = new();
_tuples = _objectList.Select(o => (o.SomeProperty1, o.SomeProperty2)).ToList();

Upvotes: 2

sudhansu63
sudhansu63

Reputation: 6200

try this.

List<Tuple<app_subjects, bool>> subjectCollection = subjectList.CovertAll( subject => new Tuple<app_subjects, bool>(){
subject,
false
}).ToList();

Upvotes: 0

dcastro
dcastro

Reputation: 68750

Like this?

subjectList.Select(s => Tuple.Create(s, false)).ToList();

Upvotes: 8

Related Questions