简体   繁体   中英

EntityFramework count members with condition C#

I have a table called LiquidatorRepresentative. The table contains the Represented Member Id. I don't know how to count how many entries in LiquidatorRepresentative have the same RepresentedMemberId in C# using EntityFramework or LinQ

Thanks in advance.

EDIT: I already made a list InfoList and now the problem is checking if there are entries with Type=15 and same RepresentedMemberId. I can't use a store procedure because the program is already running slow because of linq.

Basically, what you need - is to group data by Represented Member Id and then count items in each group. Code will be similar to:

var groups = liquidatorRepresentative.GroupBy(lr => lr.RepresentedMemberId).Select(group => new { Id = group.Key, Count = group.Count() })

foreach (var group in groups)
{
    Console.WriteLine("{0} {1}", group.Id, group.Count);
}

If you want to count the number of entities that meet a condition, then you can simply count:

var count = await (from x in set
                   where condition(x)
                   select x).CountAsync();

This will be converted into a select count(1)... on the database: it will only return the count, not all the data.

A Groupby extension method should do the trick

   var groupCount = db.LiquidatorRepresentative.GroupBy(info => info.RepresentedMemberId)
                            .Select(group => new { 
                                 RepresentedMemberId = group.Key, 
                                 Count = group.Count() 
                            });

Thank you for your help guys. I made a list with the content i needed to check and instead of forEach, i brought the first entry in element. This code works for what i needed, thanks for help.

if(InfoList.Where(adx => adx.Id == element.Id && adx.Type == "15").Count() > 1
   || InfoList.Where(adx=adx.Id == element.Id && adx.Type == "16").Count() > 1)

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