Use LINQ instead of two for loops

I want to convert these two “ugly” for loops into a LINQ expression. Can someone help me? I am 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;
}
+4
source share
3 answers

Use ReSharper :

foreach (var edge in distinctEdge)
{
    edge.value = EdgeList.Count(e => e.target == edge.target && e.source == edge.source);
}
+8
source

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();
+4
source

For completeness of the answer to the original question, I propose the following, but I do not consider it readable, like using the foreach loop suggested by @ dog-las for updating. However, I have used this method of updating all objects in a collection using LINQ recently for an easier update, so find it convenient.

var result = distinctEdge.Select(c =>
        {
            c.value = EdgeList.Count(e => e.target == c.target
                                          && e.source == c.source);
            return c;
        }).ToList();
+1
source

All Articles