Using .Zip or linq in c # to add two fields from a series of objects contained in two lists

2

I have a list of objects

List<Objeto> lista1;
List<Objeto> lista1;

Object has an attribute X and an attribute Y .

I want to do the following:

List<Objeto> listaSuma => add the values Y of each object and return this to the new list of objects ( objeto { X , Y + Y) ).

Obviously with a for loop I've already done it. I want to use Linq or Zip , but I do not know how.

PD (objects have more variables, but you do not have to do anything with them)

List<Coordenadas> result = new List<Coordenadas>();
for (int i = 0; i < list1.Count; i++)
  {
     objetAux = new Coordenadas();
     objetAux.Y = list1[i].Y + list12[i].Y;
     objetAux.X = list1[i].X;
     result.Add(objetAux);
  }
    
asked by Jesús Álvarez 11.01.2017 в 15:17
source

2 answers

1

Indeed, you can use Zip() to combine both lists with the desired result:

List<Coordenadas> result = 
    list1.Zip(
        list12,
        (primero, segundo) =>
            new Coordenadas
            {
                Y = primero.Y + segundo.Y,
                X = primero.X
            }).ToList();

Although the syntax is interesting, do not expect the performance to be better than the loop you already have.

    
answered by 11.01.2017 в 16:23
1

If I understand you correctly, all you have to do is select by generating each object as you want, something like this:

List<objeto> listaSuma = lista1.Select(l => new objeto() { x=l.x, y=l.y + l.y })
                              .ToList<objeto>();

Edit

As you comment that objeto has more properties, probably what you need is a list using a new anonymous type. This would be the code:

var listaSuma = lista1.Select(l => new { x=l.x, y=l.y + l.y }).ToList();

Edit 2

In your initial question I did not really understand what you wanted. If what you need is to join the two lists, you can effectively use Zip (from Net 4.0) and do the following:

var listaSuma  = lista1.Zip(lista2, (primero, segundo) => 
                          new { x = primero.x, y = primero.y + segundo.y }).ToList();
    
answered by 11.01.2017 в 15:29