user3220902
user3220902

Reputation: 3

Setting specific values of a list : LINQ

I have a listA that contains objects with the following properties x,y,z. also i have another listB that contain similar objects.

Now i want to select all the objects present in listA and at the same time set the z property of those objects whose A.x==B.x && A.y==B.y

List<Point> listA = //list of objects
List<Point> listB = //list of points

How do i do this?

Upvotes: 0

Views: 77

Answers (2)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

To modify listA with respect to your needs you can use following LINQ:

listA.ForEach(pA => pA.Z = listB.Where(pB => pA.X == pB.X && pA.Y == pB.Y)
                                .DefaultIfEmpty(pA)
                                .First()
                                .Z);

Then you can simply select all listA elements.

Upvotes: 1

MattSull
MattSull

Reputation: 5564

Not sure if following is what you want:

using System;
using System.Linq;
using System.Collections.Generic;

class A
{
    public double X {get; set;}
    public double Y {get; set;}
    public double Z {get; set;}
}

class B 
{
    public double X {get; set;}
    public double Y {get; set;}
    public double Z {get; set;}
}

public class Program
{
    public void Main()
    {
        var listA = new List<A>
        {
            new A {X = 1, Y = 2, Z = 3}
        };

        var listB = new List<B>
        {
            new B {X = 1, Y = 2, Z = 3}
        };

        var result = from a in listA
                     from b in listB
                     select new A
                     {
                        X = a.X,
                        Y = a.Y,
                        Z = (a.X == b.X && a.Y == b.Y) == true ? 0 : 10
                     };


        foreach(var r in result)
            Console.WriteLine(
                String.Format("{0}, {1}, {2}", r.X, r.Y, r.Z));

        // output: 1, 2, 0 because a.X == b.X && a.Y == b.Y

    }   
}

So Z is set to 0 based on a.X == b.X && a.Y == b.Y. If this condition wasn't satisfied, it would be set to 10. You can obviously decide what Z is set to yourself.

Upvotes: 0

Related Questions