How to concatenate two collections by index in LINQ

后端 未结 3 614
情深已故
情深已故 2021-02-12 08:15

What could be a LINQ equivalent to the following code?

string[] values = { \"1\", \"hello\", \"true\" };
Type[] types = { typeof(int), typeof(string), typeof(b         


        
相关标签:
3条回答
  • 2021-02-12 08:52

    Assuming both arrays have the same size:

    string[] values = { "1", "hello", "true" };
    Type[] types = { typeof(int), typeof(string), typeof(bool) };
    
    object[] objects = values
        .Select((value, index) => Convert.ChangeType(value, types[index]))
        .ToArray();
    
    0 讨论(0)
  • 2021-02-12 08:56

    .NET 4 has a Zip operator that lets you join two collections together.

    var values = { "1", "hello", "true" };
    var types = { typeof(int), typeof(string), typeof(bool) };
    var objects = values.Zip(types, (val, type) => Convert.ChangeType(val, type));
    

    The .Zip method is superior to .Select((s, i) => ...) because .Select will throw an exception when your collections don't have the same number of elements, whereas .Zip will simply zip together as many elements as it can.

    If you're on .NET 3.5, then you'll have to settle for .Select, or write your own .Zip method.

    Now, all that said, I've never used Convert.ChangeType. I'm assuming it works for your scenario, so I'll leave that be.

    0 讨论(0)
  • 2021-02-12 09:05
    object[] objects = values.Select((s,i) => Convert.ChangeType(s, types[i]))
                             .ToArray();
    
    0 讨论(0)
提交回复
热议问题