catlovespurple
catlovespurple

Reputation: 690

Use LINQ instead of two for loops

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;
}

Upvotes: 4

Views: 753

Answers (3)

Bron Thulke
Bron Thulke

Reputation: 398

For the sake of completeness answering the original question, I will propose the following BUT I don't believe it's as readable as using a foreach loop proposed by @dog-las for the update. However, I did use this method of updating all objects in a collection using LINQ recently for a simpler update, so think it's handy.

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

Upvotes: 1

Rohit
Rohit

Reputation: 10236

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();

Upvotes: 4

Backs
Backs

Reputation: 24903

Use ReSharper:

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

Upvotes: 8

Related Questions