简体   繁体   中英

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.

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM