2017-04-21 90 views
1

我有一個linq查詢在我的aspnet核心應用程序返回更多的行,那麼它應該。查詢如下。如何做一個linq組

public List<csAutoComplete> GetAutoComplete(string Type, string filter) 
{ 
string[] GasCodesnotListed = { "F97", "F98", "F99" }; 
Model1 = from x in _context.TblGascodes 
    where ((x.GasCode.StartsWith("F13") || x.GasName.StartsWith("F13")) && 
      !GasCodesnotListed.Contains(x.FedclusterCode)) 
    orderby x.GasCode 
    group x by new csAutoComplete { ACCode = x.GasCode, ACName = x.GasName } into Alpha 
    select new csAutoComplete <=== (Is this the issue???) 
     { 
     ACCode = Alpha.Key.ACCode, 
     ACName = Alpha.Key.ACCode + " - " + Alpha.Key.ACName 
     }; 
return Model1.ToList(); 
} 

} 回報(7)導致

所以我粘貼到LINQ墊,並得到了結果,我預計(1)

string[] GasCodesnotListed = { "F97", "F98", "F99" }; 
TblGasCodes 
    .Where (
     x => 
     ((x.GasCode.StartsWith ("F13") || x.GasName.StartsWith ("F13")) && 
      !(GasCodesnotListed.Contains (x.GasCode)) 
     ) 
    ) 
    .OrderBy (x => x.GasCode) 
    .GroupBy (
     x => 
     new 
     { 
      ACCode = x.GasCode, 
      ACName = x.GasName 
     } 
    ) 
    .Select (
     Alpha => 
     new 
     { 
      ACCode = Alpha.Key.ACCode, 
      ACName = ((Alpha.Key.ACCode + " - ") + Alpha.Key.ACName) 
     } 
    ) 

唯一的區別似乎是在新的csAutoComplete。如果這是一個類定義,爲什麼這應該有所作爲?我該如何解決這個問題。

+0

如果'csAutoComplete'沒有覆蓋'Equals',它將通過Object.ReferenceEquals()進行比較,而爲了GroupBy的目的,匿名類型(如第二個示例中)是相同的,如果所有屬性是相同的。我會使用匿名類型進行分組。 –

+0

當你說匿名類型時,我不明白這一點。你的意思是創建新變量並刪除類? –

+1

在你的第二個版本中,你有'new ACCode = x.GasCode, ACName = x.GasName }' - 你正在創建一個匿名類型的實例。 –

回答

0

除非您不會覆蓋EqualscsAutoComplete,GroupBy將使用Object.ReferenceEquals()或某些等價物比較csAutoComplete的實例。具有相同GasCodeGasName屬性的兩個實例將是兩個獨立的組密鑰。如果你有七件物品進來,它們將分成七組,每組一件。

匿名類型不是這種情況。具有相同屬性值的獨立實例在GroupBy之間將被視爲相等。如果你喜歡住在邊緣或過載EqualscsAutoComplete -

var items = new[] { 0, 0 }.Select(n => new { x = n, y = n.ToString() }).ToArray(); 

var groups = items.GroupBy(x => x).ToArray(); 

// Not equal here! 
var aretheyequal = items[0] == items[1]; 

// But GroupBy isn't fooled: There's only one group 
var groupcount = groups.Length; 

使用您的匿名類型的一組密鑰。根據我的經驗(或者更準確地說,程序員通過不注意引入的更改而編寫有趣的錯誤),可能會導致有趣的錯誤。我不想去那裏。

因此,我認爲你的GetAutoComplete方法是確定的,除了通過線組,我就改成這樣:

group x by new { ACCode = x.GasCode, ACName = x.GasName } into Alpha 

後來參考ACCode = Alpha.Key.ACCode等應該不需要改變,因爲屬性名稱是相同的。

+1

這是正確的,當它是對象的LINQ。不過,我認爲'_context。TblGascodes'不是'IEnumerable',而是來自Entity Framework或LINQ to SQL的'IQueryable'。因此,表達式Model1作爲一個整體將被轉換爲SQL,並且有或沒有'csAutoComplete'的分組不應該有所作爲。 @湯姆,你能談談這個嗎? –

0

在你的代碼,似乎是在GasCodesnotListed.Contains(一個着眼於FedclusterCode,另一個在GasCode)一個重要的區別:

where (x.GasCode.StartsWith ("F13") && !GasCodesnotListed.Contains (x.**FedclusterCode**)) 

... ...與

.Where (
    x => 
    (
     x.GasCode.StartsWith ("F13") && 
     !(GasCodesnotListed.Contains (x.**GasCode**)) 
    ) 
)