Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an anonymous type with calculated values

Tags:

c#

linq

Let's say I have this structure:

class Ticket
{
 int Id;
 bool Void;
}

Is it possible to use LINQ to get an Anonymous Type with this two aggregated properties?

select new {totalVoid = numVoidTickets, totalNonVoid = numNonVoidTickets};

I thought this could be an approach:

from t in Tickets
select new { totalVoid = t.Id.Count(x => x.Void == true, 
totalNonVoid = t.Id.Count(x => x.Void == false };

but intellisense is not showing Count() after I type t.Id nor t.

like image 272
Nicolás Lope de Barrios Avatar asked Jan 19 '26 15:01

Nicolás Lope de Barrios


1 Answers

t is single item in your expression.

You don't need outer Select / 'from` to get this information:

var result = new 
{ 
  totalVoid = Tickets.Count(x => x.Void == true), 
  totalNonVoid = Tickets.Count(x => x.Void == false)
};
like image 169
Alexei Levenkov Avatar answered Jan 21 '26 03:01

Alexei Levenkov