2017-01-20 55 views
1

基本上我有一個由數據庫填充的List<Indicator>在Linq中使用左連接c#

public class Indicator 
{ 
    public string Month { get; set; } 
    public Int NumberOfHouses { get; set; } 
    public string City { get; set; } 
} 

我做我的查詢和數據庫建模的方式,將需要很長時間才能「做出正確的事情」,所以我想解決這個使用linq

我會在列表上始終有N City。即使沒有關聯數據庫的Month記錄,我也要重複它們。像左連接一樣。

所以,如果我有這樣的:

Jan/2017  10  CityA 
Jan/2017  12  CityB 
Jan/2017  16  CityC 
Dec/2016  33  CityC 
Nov/2016  21  CityC 

這是預期的結果:

Jan/2017  10  CityA 
Jan/2017  12  CityB 
Jan/2017  16  CityC 
Dec/2016  0  CityA 
Dec/2016  0  CityB 
Dec/2016  33  CityC 
Nov/2016  0  CityA 
Nov/2016  0  CityB 
Nov/2016  21  CityC 

是否有可能使用Linq解決這個問題?

+0

是有可能產生零,但你有沒有試着寫LINQ查詢? –

+0

@EhsanSajjad謝謝 - 但已經太遲了,已經回答了這個問題。他得到了stackoverflow爲他做他的課程作業。這不是很酷的Marllon。 – buffjape

+0

@EhsanSajjad是的,但不喜歡buffjape的。我理解你buffjape,但我總是試圖直接在SQL上解決這類問題..我有一個解決方案,但不使用'Linq'。這就是我尋求幫助的原因 - 尋求更清潔更好的解決方案。謝謝! –

回答

1

是的,這是可能的。

// All the Indicator records 
IQueryable<Indicator> data = _context.Indicators; 

// All months from database 
IQueryable<string> months = data.Select(i => i.Month).Distinct(); 

// All cities 
IQueryable<string> cities = data.Select(i => i.City).Distinct(); 

// Now your query 
var results = (from string month in months 
       from string city in cities 
       select new 
       { 
        month = month, 
        city = city, 
        count = data.Where(i => i.Month == month && i.City == city) 
           .Select(i => i.NumberOfHouses) 
           .FirstOrDefault() 
       }).ToList(); 

當記錄丟失,由.FirstOrDefault()因爲default(int) == 0

+0

而不是匿名類型查詢甚至可以返回'Indicator's。 – wkl

+0

是的,我只是用一些'OrderBy'把通用列表再次改爲'Indicator'。謝謝buffjape。 –