问题
I have this in my code:
var pRating = ctx.PrProjectRating
.Where(x => x.PrIsDeleted == false)
.Select(k => k)
.GroupBy(g =>
new {g.PrPIdG},
(key, group) => new
{
sumR = group.Sum(k => k.PrValue),
pidG = key.PrPIdG
});
var pLike = ctx.PlProjectLike
.Where(x => x.PlValue == "Like")
.Select(c => c)
.GroupBy(g =>
new {g.PlPIdG},
(key, group) => new
{
sumR = group.Count(),
pidG = key.PlPIdG
})
.OrderByDescending(g => g.sumR);
var pConnect = ctx.PcProjectConnect
.Where(x => x.PcStatus == "Connected")
.Select(c => c)
.GroupBy(g =>
new {g.PcPIdG},
(key, group) => new
{
sumR = group.Count(),
pidG = key.PcPIdG
})
.OrderByDescending(g => g.sumR);
How do i combine these collections and sum the sumR value together?
EDIT
pRating =
pidG sumR
123 11
124 7
125 5
pLike =
pidG sumR
123 3
125 2
pConnect =
pidG sumR
125 5
Result should be:
pResult =
pidG sumR
123 15
125 12
124 7
i need to group the pidG together and sum them up using sumR
I wanted to get the list of pidG values group them and find the count or sum and order them by the highest sum value and thats what you see in the collections above and in the table diagram.
Then i need to grab the sum and group the collections to find that its ordered by the highest value of sumR
EDIT
im trying to do this:
var query =
from i in ids
join ra in ratings on i equals ra.Id into rs
from ra in rs.DefaultIfEmpty()
join l in likes on i equals l.Id into ls
from l in ls.DefaultIfEmpty()
join co in connects on i equals co.Id into cs
from co in cs.DefaultIfEmpty()
select new
{
Id = i,
Total = ra?.Sum ?? 0 + l?.Count ?? 0 + co?.Count ?? 0,
Ratings = ra?.Sum ?? 0,
Likes = l?.Count ?? 0,
Connects = co?.Count ?? 0,
};
query = query.OrderByDescending(x => x.Total);
But does not sum the total which i need.
回答1:
You should be able to just do all the queries separately as subqueries, then do a full join to combine the results on the client.
var ratings =
from r in ctx.PrProjectRating
where !r.PrIsDeleted
group r.PrValue by r.PrPIdG into g
select new
{
Id = g.Key,
Sum = g.Sum(),
};
var likes =
from l in ctx.PlProjectLike
where l.PlValue == "Like"
group 1 by l.PlPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var connects =
from c in ctx.PcProjectConnect
where c.PcStatus == "Connected"
group 1 by c.PcPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var ids = ratings.Select(r => r.Id)
.Union(likes.Select(l => l.Id))
.Union(connects.Select(c => c.Id))
.ToHashSet();
var query =
from i in ids
join r in ratings on i equals r.Id into rs
from r in rs.DefaultIfEmpty()
join l in likes on i equals l.Id into ls
from l in ls.DefaultIfEmpty()
join c in connects on i equals c.Id into cs
from c in cs.DefaultIfEmpty()
select new
{
Id = i,
Ratings = r?.Sum ?? 0,
Likes = l?.Count ?? 0,
Connects = c?.Count ?? 0,
};
来源:https://stackoverflow.com/questions/65014531/summing-a-value-inside-of-a-anonymous-type