locked
Setting property of IEnumerable to adjacent item in second IEnumerable RRS feed

  • Question

  • I'm just querying as to whether there's a concise way of performing this action in C#, rather than having to perform it manually. What I'm trying to do is set the property of each instance of the first IEnumerable to the adjacent value in a second IEnumerable.

    So the classes used by both are as follows:

    public class Class1
    {
        public int x { get; set; }
        public Class2 class2 { get; set; }
    }
    
    public class Class2
    {
        public int y { get; set; }
    }

    So I want to iterate through the first IEnumerable for Class1 and set the "class2" property to the adjacent item in the second IEnumerable of type Class2, if that makes sense.

    Is there a better/shorthand way of doing this other than looping through the items and setting the property manually?


    • Edited by Porl91 Wednesday, March 18, 2015 9:35 PM Typo
    Wednesday, March 18, 2015 9:34 PM

Answers

  • Hi. You could use the Linq Zip method to achieve that. See the example below (also note calling ToList() force the expression to execute).

    //using System.Linq;
    
    var c1s = new List<Class1>{
        new Class1 { x = 1},
        new Class1 { x = 2},
        new Class1 { x = 3},
        new Class1 { x = 4},
        new Class1 { x = 5},
    };
    
    var c2s = new List<Class2>{
        new Class2 { y = 1},
        new Class2 { y = 2},
        new Class2 { y = 3},
        new Class2 { y = 4},
        new Class2 { y = 5}
    };
    
    c1s.Zip(c2s, (c1, c2) => c1.class2 = c2).ToList();

    • Marked as answer by Porl91 Wednesday, March 18, 2015 11:43 PM
    Wednesday, March 18, 2015 11:20 PM

All replies

  • Hi. You could use the Linq Zip method to achieve that. See the example below (also note calling ToList() force the expression to execute).

    //using System.Linq;
    
    var c1s = new List<Class1>{
        new Class1 { x = 1},
        new Class1 { x = 2},
        new Class1 { x = 3},
        new Class1 { x = 4},
        new Class1 { x = 5},
    };
    
    var c2s = new List<Class2>{
        new Class2 { y = 1},
        new Class2 { y = 2},
        new Class2 { y = 3},
        new Class2 { y = 4},
        new Class2 { y = 5}
    };
    
    c1s.Zip(c2s, (c1, c2) => c1.class2 = c2).ToList();

    • Marked as answer by Porl91 Wednesday, March 18, 2015 11:43 PM
    Wednesday, March 18, 2015 11:20 PM
  • Fantastic. :) That's exactly what I was after. Thanks!
    Wednesday, March 18, 2015 11:43 PM