简体   繁体   中英

To write a linq query to get selected name count

Here I need to get the total count of name Murugan my output should be "2" . How to write Linq Query for that

Linq:

Person[] names = {new Person { Name = "Murugan", Money = 15000 },
                                 new Person{Name="Vel",Money=17000},
                                 new Person{Name="Murugan",Money=1000},
                                  new Person{Name="Subramani",Money=18000},
                                 new Person{Name="Vel",Money=2500}};
var result = from val in names
         where val.Name == "Murugan" 
         select val;
Console.WriteLine(result);
Console.ReadLine();

尝试这个:

var count = names.Count(x=>x.Name=="Murugan");

You can use this,

var result = (from val in names
                          where val.Name == "Murugan"
                          select val).Count();

you can use this:

  var result = from val in names
               where val.Name == "Murugan"
               group val by val.Name into g
               select new { Count = g.Count()                   
               };

try:

Person[] names = { new Person { Name = "Murugan", Money = 15000 },
                   new Person{Name="Vel",Money=17000},
                   new Person{Name="Murugan",Money=1000},
                   new Person{Name="Subramani",Money=18000},
                   new Person{Name="Vel",Money=2500} };

var result = (from val in names
              where val.Name == "Murugan"
              select val).ToList();

Console.WriteLine(result.Count);
Console.ReadLine();
var result = (from val in names
                         where val.Name == "Murugan"
                         select val).Count ();

linq returns IEnumerable which has Count ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM