Accepted answer

you can use following code:

var count = => 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 ( > 0 && data.trygetvalue(, out cdat))
                             // do some operation. (var cdata = sumdata(,

                             return true;
                         return false;


@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,
         record ++;


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.


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