devklick
devklick

Reputation: 2629

List of complex objects to list of named tuples

Given a List<ComplexObject>, how can I create a new list of named tuples? So for every ComplexObject in the original list, create a new tuple with certain values from the ComplexObject?

public class ComplexObject 
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
    public bool SomeBool { get; set; }
    // More properties that are irrelevant for the purpose of this question...
}

This is what I'm trying:

List<ComplexObject> complexObjects = new List<ComplexObject>
{
    new ComplexObject { SomeString = "SomeString01", SomeInt = 1, SomeBool = true },
    new ComplexObject { SomeString = "SomeString02", SomeInt = 2, SomeBool = false },
    new ComplexObject { SomeString = "SomeString03", SomeInt = 3, SomeBool = true },
};

List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples 
    = complexObjects.SelectMany(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool));

However this results in an error:

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Upvotes: 1

Views: 747

Answers (2)

Fabjan
Fabjan

Reputation: 13676

Well, method SelectMany flattens the collection of collections to a single collection and since it's not the case here you don't need to use this function.

So instead we will use .Select. Don't forget that .Select returns IEnumerable<T> and if we try to assign it to List<T> it will fail.

You could change your code to:

List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples
                = complexObjects.Select(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool)).ToList();

And it works as expected now.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500385

You're nearly there, with just two problems:

  • You need to use Select rather than SelectMany, are you're just performing a 1:1 transform
  • You need a call to ToList to get a List<T> rather than IEnumerable<T>:
List<(string SomeString, int SomeInt, bool SomeBool)> complexTuples =
    complexObjects.Select(obj => (obj.SomeString, obj.SomeInt, obj.SomeBool)).ToList();

Upvotes: 2

Related Questions