幾天前我用 SQL 提出了同樣的問題,但現在它出現在 C# 代碼中
假設我們有這樣一個類來保存不同的 id/text 對:
public class Text {
public int id { get; set; }
public string text { get; set; }
...
}
現在讓我們填充一些資料,ListA 得到很多資料:
List<Text> ListA = new List<Text>{
new () {id = 1, text = "aaa1"},
new () {id = 2, text = "aaa2"},
new () {id = 3, text = "aaa3"},
new () {id = 4, text = "aaa4"},
new () {id = 5, text = "aaa5"},
new () {id = 6, text = "aaa6"},
};
ListB 只得到一點點資料:
List<Text> ListB = new List<Text>{
new () {id = 4, text = "bbb4"},
new () {id = 5, text = "bbb5"},
};
現在我們正在尋找什么:
var result = ... // Some Linq or Lambda magic goes here
// and if we do:
foreach(var item in result){
Console.WriteLine(item.Id " " item.Text);
}
// Result will be:
1 : aaa1
2 : aaa2
3 : aaa3
4 : bbb4
5 : bbb5
6 : aaa6
uj5u.com熱心網友回復:
id您可以嘗試在以下范圍內尋找ListB:
var result = ListA
.Select(a => ListB.FirstOrDefault(b => b.id == a.id) ?? a);
在這里,對于每個inside,我們嘗試通過( ) 內的專案a找到對應的。如果沒有找到這樣的專案,我們只回傳專案:ListAidb.id == a.idListBListA ?? item
如果是 .Net 6,您可以使用多載.FirstOrDefault版本(我們可以a作為默認值傳遞):
var result = ListA
.Select(a => ListB.FirstOrDefault(b => a.id == b.id, a));
uj5u.com熱心網友回復:
ListB首先轉換為 Dictionary
可能更有效:var dictB = ListB.ToDictionary(x=> x.id)
然后你可以寫
var result = ListA.Select(x => dictB.TryGetValue(x.id, out var b) ? b : x)
UPD 重寫考慮了評論建議
uj5u.com熱心網友回復:
一種選擇是Union通過指定EqualityComparer. 如果順序很重要,可以OrderBy在最后做一個操作。
class TextIdComparer : EqualityComparer<Text> {
public override bool Equals(Text x, Text y) => x.id == y.id;
}
var result = ListB.Union(ListA, new TextIdComparer()).OrderBy(x => x.id)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/463223.html
上一篇:Linq按元素和子元素分組
下一篇:asp.netlinq按id分組
