score:0

Accepted answer

You can use following code:

var count = RangeData.Select(x => new { Id = x.Item1?.port?.id ?? x.Item2?.port?.id ?? 0, Item = x })
                     .Count(x =>
                     {
                         int? cdate = null; // change int to your desired type over here
                         if (x.Id > 0 && Data.Trygetvalue(x.Id, out cdat))
                         {
                             // Do some operation. (var cdata = SumData(x.Id, x.Item.Item2.port.Date)

                             return true;
                         }
                         return false;
                     });

Edit:

@D Stanley is completely right, LINQ is wrong tool over here. You can refactor few bits of your code though:

var Date1 = RangeData.ToList();
int record =0;
foreach (var tr in Date1)
{
    int? cdat = null; // change int to your desired type over here
    int id = tr.Item1?.port?.id ?? tr.Item2?.port?.id ?? 0;
    if (id >0 && Data.Trygetvalue(id, out cdat))
    { 
         // Do some operation. (var cdata = SumData(id, tr.Item2.port.Date)
         record ++;
    }
}

score:2

I think your code example is false, your record variable is initialized to 0 on each loop so increment it is useless .

I suppose that you want to count records in your list which have an id, you can achieve this with one single Count() :

var record = Date1.Count(o => (o.Item1?.port?.id ?? o.Item2?.port?.id) > 0);

score:0

Linq is not the right tool here. Linq is for converting or querying a collection. You are looping over a collection and "doing some operation". Depending on what that operation is, trying to shoehorn it into a Linq statement will be harder to understand to an outside reader, difficult to debug, and hard to maintain.

There is absolutely nothing wrong with the loop that you have. As you can tell from the other answers, it's difficult to wedge all of the information you have into a "single-line" statement just to use Linq.


Related Articles