1

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.

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.