Water
Water

Reputation: 1192

How to convert this to Linq?

I got another Linq problem.. Because I'm not really sure if there is another way to do this. Here is what I want to convert:

class ID
{
 public string name {get; set;}
 public int id {get; set;}
}

ID[] num1 = new ID[2] { {"david",1} , {"mark",2} };
ID[] num2 = new ID[3] { {"david",1} , {"david",2} };

for(int i = 0; i < num1.Length; i++)
{
 for(int j = 0; j < num2.Length; j++)
 {
  if(num1.name.Equals(num2.name) && num1.num == num2.num)
  {
   Console.Writeline("name: " + num1.name + " id: " + num1.id);
   //Do something
   break; //to avoid useless iterations once found
  }
 }
}

It's not a perfect code, but hopefully it captures what I want to do. Currently I am implementing this in Linq like such:

var match = 
from a in num1
from b in num2
where (a.name.Equals(b.name) && a.num == b.num)
select a;
//do something with match

I'm pretty new to Linq so I'm not sure if this is the best way to do it or is there a much more "simpler" way. Since it seems like I'm just converting it to linq but essentially does the same code.

Thank you!

Upvotes: 0

Views: 61

Answers (1)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

The Linq code you wrote is already on the right track to solve the problem, though it is not the only way to solve it.

Instead of using a where clause, you could override the Equals method on the class, or implement an IEqualityComaprer<Number>. Then you could use the Intersect Linq method.

Something like this:

public class Number
{
    public override bool Equals(object other)
    {
        var otherAsNumber = other as Number;
        return otherAsNumber != null
            && (otherAsNumber.Name == null
                ? this.Name == null
                : otherAsNumber.Name.Equals(this.Name)
            )
            && otherAsNumber.Num == this.Num
            ;
    }

    // ...
}

// ...

var result = num1.Intersect(num2);

foreach(var item in result)
{
    // Do something
}

This of course assumes that you've fixed your code so that it compiles, and so that num1 and num2 refer to collections of Number classes, instead of individual Number instances. There are a lot of problems in the code you wrote, so I'll leave fixing that problem to you.

Upvotes: 1

Related Questions