我目前正在開發一個 .NET 應用程式。我需要撰寫一個 LINQ 查詢來過濾List<SearchResult>下面示例中給定的。
允許CompanyId ContactId或CompanyId(不帶 ContactId)的組合作為結果的鍵,結果串列中的條目必須是不同的。
結果串列中的鍵是唯一的“CompanyID ContactId”或唯一的“CompanyID”的組合。例如,在作為鍵的結果串列中,我可以有一個“companyID 1”和多個“companyID 1” ContactID (1, 2, 3, ...) 但是每個 ContactID 只能與一個 CompanyID 組合一次即{1},{1, 1}, {1, 2}, {1, 3}但不是第二次{1, 1}或{1}。
public class SearchResult
{
public int? CompanyId {get; set;}
public int? ContactId {get; set;}
}
public class Program
{
public static void Main()
{
var searchResults = new List<SearchResult>
{
new SearchResult { CompanyId = 1, ContactId = 1 }, // yes
new SearchResult { CompanyId = 2, ContactId = 3 }, // yes
new SearchResult { CompanyId = 2, ContactId = 4 }, // yes
new SearchResult { CompanyId = 1 }, // yes
new SearchResult { CompanyId = 2 }, // yes
new SearchResult { CompanyId = 1, ContactId = 1 }, // no
new SearchResult { CompanyId = 1 }, // no
new SearchResult { }, // no
new SearchResult { CompanyId = null }, // no
new SearchResult { CompanyId = null, ContactId = null }, // no
new SearchResult { ContactId = null }, // no
};
// Unfortunately my LINQ query doesn't work correctly
var result = searchResults
.GroupBy(sr => sr.CompanyId)
.Select(grp => grp.First());
foreach(SearchResult sr in result){
Console.WriteLine(sr.CompanyId " " sr.ContactId);
}
}
}
我當前的 LINQ 查詢無法正常作業 - 它也很基本。我只得到結果:[{1, 1},{2, 3}],這真的很棘手。
雖然想要的結果應該是[{1, 1},{2, 3},{2, 4}, {1},{2}].
你知道如何檢索正確的結果嗎?
uj5u.com熱心網友回復:
非常接近,但是.GroupBy兩者CompanyId和ContactId(而不僅僅是CompanyId)& 然后使用.First().
var result = searchResults
.GroupBy(sr => new { sr.CompanyId, sr.ContactId })
.Select(x => x.First());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318206.html
上一篇:InvalidOperationException:無法翻譯LINQ運算式
下一篇:.NETLinq查詢一對多關系
