SledgeHammer SledgeHammer - 1 year ago 89
C# Question

How to do in Linq?

I have 2 separate arrays (coming from Json, but that's not important). They are lined up... i.e. arr1[1] goes with arr2[1].

I want to create a list of Test objects with a few catches:

1) both arr1 and arr2 value can't be null
2) I'm only interested in indexes where the arr1 element is a multiple of 5


This is what I have so far:

class Test
{
public double d1;
public double d2;
}

class Program
{
static void Main(string[] args)
{
string[] arr1 = new string[] { "0", "2", "5", "7", "10", "11", null, "13", "15" };
string[] arr2 = new string[] { "11", "13", "56", "8", null, "44", "55", "66", "77" };

var v = arr1.Where(x => !String.IsNullOrEmpty(x)).Select(x => Double.Parse(x)).Where(x => (x % 5) == 0).Select((x, y) => new Test
{
d1 = x,
d2 = Double.Parse(arr2[y])
});
}
}


I'm not sure how to skip the ones where arr2 is null though and the alignment is getting messed up.

LB2 LB2
Answer Source

In order not to mess up alignment, you should first .Zip the two arrays. Then, if I understand correctly, those indices that have null as value in either array should be skipped, so you filter those out with .Where, then do the rest of your logic.

class Test
{
    public double d1;
    public double d2;
}

class Program
{
    static void Main(string[] args)
    {
        string[] arr1 = new string[] { "0", "2", "5", "7", "10", "11", null, "13", "15" };
        string[] arr2 = new string[] { "11", "13", "56", "8", null, "44", "55", "66", "77" };

        var v = arr1
            .Zip(arr2, (x, y) = new {x, y})
            .Where(a => !string.IsNullOrEmpty(a.x) && !string.IsNullOrEmpty(a.y))
            .Select(a => new Test { d1 = double.Parse(a.x), d2 = double.Parse(a.y))
            .Where(a => (a.d1 % 5) == 0);

       // TODO, ready to enumerate over v.
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download