Home > Net >  LINQ QUERY TABLE
LINQ QUERY TABLE

Time:12-07

The number increases by 1 in the database as a staff member views something. Example

abab : 1
cbcb : 1
dcdc: 1
abab : 1
abab : 1

I want to print who viewed how much in the table. Example

abab : 3
cbcb : 1
dcdc : 1

but it doesn't work the way I want. The code I wrote is below

Count = _viewHistoryRepository.GetByExpression(f => f.MemberId == c.MemberId).Sum(s=> s.ViewsCount)

Output:

abab : 3
abab : 3
abab : 3
cbcb : 1
dcdc: 1

I want each name to appear once. Thank you

CodePudding user response:

You need to use GroupBy then:

IEnumerable<string> query = _viewHistoryRepository
    .GroupBy(x => x.MemberId)
    .Select(g => $"{g.Key} : {g.Sum(x => x.ViewsCount)}");

CodePudding user response:

So apparently you have a class similar to this:

class StaffMemberView
{
    public string Name {get; set;}
    public int ViewCount {get; set;}   // in your input always 1
    ... // other properties
}

If your input indeed always have a value 1, it is enough to make groups of StaffMemberviews that have the same value for property Name. In parameter resultSelector count the number of elements in each group:

IEnumerable<StaffMemberView> staffMemberViews = ...
var result = staffMemberViews.GroupBy(

    // keySelector: make groups with the same value for Name:
    staffMemberView => staffMemberView.Name,

    // parameter resultSelector, for every Name, and all StaffMemberViews that 
    // have this Name, make one new:
    (name, staffMembersViewsWithThisName) => new 
    {
        Name = name,
        ViewCount = staffMemberViewsWithThisName.Count(),
    });

If parameter ViewCount sometimes is not 1, then it is not enough to just Count the StaffMemberViews in each group, but you have to Sum the values of ViewCount.

Parameter resultSelector changes:

(name, staffMembersViewsWithThisName) => new 
{
    Name = name,
    ViewCount = staffMemberViewsWithThisName
                .Select(staffMemberView => staffMemberView.ViewCount)
                .Sum(),
});
  • Related