Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LINQ instead of two for loops

Tags:

c#

linq

I want to convert these two "ugly" for loops to a LINQ expression. Can anyone help me out? I am pretty new to LINQ. thanks in advance!

foreach (Edge edge in distinctEdge)
{
    var c = 0;
    foreach(Edge e in EdgeList)
    {
        if(e.target == edge.target && e.source == edge.source)
        {
            c++;
        }
    }
    edge.value = c;
}
like image 255
catlovespurple Avatar asked Dec 10 '22 21:12

catlovespurple


2 Answers

Use ReSharper:

foreach (var edge in distinctEdge)
{
    edge.value = EdgeList.Count(e => e.target == edge.target && e.source == edge.source);
}
like image 75
Backs Avatar answered Dec 13 '22 10:12

Backs


Something easy to read and understand

  var value=(from edge in distinctEdge
    join e in EdgeList
   on edge.Target equals e.Target
   and e.source equals edge.source
   select edge ).Count();
like image 23
Rohit Avatar answered Dec 13 '22 10:12

Rohit