我希望從 ListA 中獲取專案,其中兩個串列中的 Id 值相同,并且串列 A 或串列 B 中的 Id 計數必須大于 1
var items = itemsA.Where(x => itemsB.Select(y => y.Id == x.Id).Count() > 1);
這給了我在 itemsB 中的相同 ID 大于 1 的結果,我想使用 or 條件來檢查 itemsA 中的相同計數器
Eg 1:
ListA=[{"id"=1,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=2","name="xyz"}, {"id=1, "name"="mno"}]
Should return [{"id"=1,"name="abc"},{"id=1, "name"="def"}] because id =1 exists in listB and the count of id with value 1 in listA is more then 1.
Eg 2:
ListA=[{"id"=2,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=1","name="xyz"}, {"id=1, "name"="mno"}]
should return {"id=1, "name"="def"} because common id in both list is 1 and the count of id with value 1 in ListB is more then 1.
uj5u.com熱心網友回復:
我不確定這是最好的解決方案,但據我了解這個問題,它應該是一個解決方案。
假設你有一個Item類如下:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
itemsA并將and定義itemsB為List<Item>s,您可以首先找到Id兩個串列中存在的所有 s,然后根據每個串列itemsA中每個串列的出現選擇適用的專案Id:
IEnumerable<int> idsInBothItemLists = itemsA
.Select(a => a.Id)
.Intersect(itemsB.Select(b => b.Id))
.Distinct();
List<Item> items = itemsA
.Where(a => idsInBothItemLists.Contains(a.Id))
.GroupBy(a => a.Id)
.Where(gr =>
gr.Skip(1).Any() ||
itemsB.Where(b => b.Id == gr.Key).Skip(1).Any())
.SelectMany(gr => gr.Select(item => item))
.ToList();
(與您的原始代碼中.Skip(1).Any()的目的相同.Count() > 1;它只是檢查跳過第一項后是否還有任何專案。)
itemsA列印來自和的建議人口的輸出itemsB
foreach (var entry in items)
{
Console.WriteLine(entry.Id " " entry.Name);
}
例如輸入
var itemsA = new List<Item>
{
new Item { Id = 1, Name = "abc" },
new Item { Id = 3, Name = "def" },
new Item { Id = 1, Name = "ghi" },
new Item { Id = 2, Name = "jkl" }
};
var itemsB = new List<Item>
{
new Item { Id = 2, Name = "xyz" },
new Item { Id = 2, Name = "jkl" },
new Item { Id = 1, Name = "mno" },
new Item { Id = 3, Name = "pqr" }
};
給
1 abc
1 ghi
2 jkl
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/424688.html
上一篇:使用linq根據包含IEnumerable<Guid>的另一個串列過濾串列
下一篇:ASP.net(按鈕)
