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: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.

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

Related Query

More Query from same tag