开发者

3 arrays to 1 IEnumerable<test>

开发者 https://www.devze.com 2023-02-21 22:18 出处:网络
Lets say I have this: public class test { int foo; int foo2; string foo3; } int[] foo = new int[] { 1, 2, 3 }开发者_JAVA百科;

Lets say I have this:

 public class test
 {
     int foo;
     int foo2;
     string foo3;
 }

 int[] foo = new int[] { 1, 2, 3 }开发者_JAVA百科;
 int[] foo2 = new int[] { 4, 5, 6 };
 string[] foo3 = new string[] { "a", "b", "c" };

How can I turn those 3 arrays to IEnumberable of test?

TIA

/Lasse


You can use the .NET 4.0 Enumerable.Zip extension method:

foo.Zip(foo2, (first, second) => new { first, second })
    .Zip(foo3, (left, right) => new test
    {
        foo = left.first, 
        foo2 = left.second, 
        foo3 = right
    });

Or write a method that does this:

public static IEnumerable<test> FooCombiner(int[] foo,
    int[] foo2, string[] foo3)
{
    for (int index = 0; index < foo.Length; index++)
    {
        yield return new test
        {
            foo = foo[index], 
            foo2 = foo2[index], 
            foo3 = foo3[index]
        };
    }
}

The last example is the most readable IMO.


public static IEnumerable<test> Test(int[] foo, int[] foo2, string[] foo3)
{
    // do some length checking
    for (int i = 0; i < foo.Length; i++)
    {
        yield return new test()
        {
            foo = foo[i],
            foo2 = foo2[i],
            foo3 = foo3[i]
        };
    }
}

You can add some length checking or make it with foreach, but i think idea is shown


You can use this code if you don't like loops:

List<test> result = Enumerable.Range(0, foo.Length).Select(i => new test() { foo = foo[i], foo2 = foo2[i], foo3 = foo3[i] }).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号