Left outer join and group by

丶灬走出姿态 提交于 2019-12-04 09:14:31

There is a way to left join in LINQ, but it's true - the syntax is not that clear. Your query would look like this:

var query = from year in years
            join data in myData
                on year equals (data.Expiration.Year - DateTime.Now.Year) + 1
                into year_data
            from y_d in year_data.DefaultIfEmpty()
            group y_d by new
            {
                Year = year,
                Name = y_d == null ? "" : y_d.Name
            }
            into grouped
            select new
            {
                Name = grouped.Key.Name,
                Year = grouped.Key.Year,
                Value = grouped.Sum(d => d == null ? 0 : d.Quantity * d.Price)
            };

You can also take different approach - instead of joining, select all years first and filter out your data while computing aggregate for each data object / year. Like this:

from year in years select new 
{ 
    Year = year, 
    Items = myData
        .GroupBy(i => i.Name)
        .Select(grouped => new 
        { 
            Name = grouped.Key, 
            Aggregate = grouped
                .Where(d => (d.Expiration.Year - DateTime.Now.Year) + 1 == year)
                .Sum(d => d.Price * d.Quantity)
        })
};

if you can't solve the problem ... replace it ...

build dummy entries of MyData for each name and year with quantity=0 and price=0

put them in a list and replace this line:

var query = from data in myData

with this line:

var query = from data in myData.Concat(dummyList)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!