我想根據某些條件(使用 LINQ)制作一組三個。假設我有一個班級:
class Collection
{
public int id;
public string name;
public double weight;
}
然后我正在創建集合:
List<Collection> collection1 = new()
{
new Collection() { id = 11, name = "Abraham 1", weight = 1.1 },
new Collection() { id = 12, name = "Abraham 2", weight = 1.2 },
new Collection() { id = 13, name = "Abraham 3", weight = 1.3 },
};
List<Collection> collection2 = new()
{
new Collection() { id = 21, name = "Bill 1", weight = 2.1 },
new Collection() { id = 22, name = "Bill 2", weight = 2.2 },
new Collection() { id = 23, name = "Bill 3", weight = 2.3 },
};
List<Collection> collection3 = new()
{
new Collection() { id = 31, name = "David 1", weight = 3.1 },
new Collection() { id = 32, name = "David 2", weight = 3.2 },
new Collection() { id = 33, name = "David 3", weight = 3.3 },
};
TODO 1. 條件:從第 1 個集合中獲取第 1 列,從第 2 個集合中獲取第 2 列,從第 3 列中獲取第 3 列。結果應該是:
{
new Collection() { id = 11, name = "Bill 1", weight = 3.1 },
new Collection() { id = 12, name = "Bill 2", weight = 3.2 },
new Collection() { id = 13, name = "Bill 3", weight = 3.1 }
}
TODO 2. 第二種情況:從所有集合的列中獲取第一個元素。結果應該是:
{
new Collection() { id = 11, name = "Abraham 1", weight = 1.1 },
new Collection() { id = 21, name = "Bill 1", weight = 2.1 },
new Collection() { id = 31, name = "David 1", weight = 3.1 }
}
請幫忙。
uj5u.com熱心網友回復:
使用 C# 10 和 .Net 6,只需使用Enumerable.Zip:
var todo1 = collection1.Zip(collection2, collection3)
.Select(t => new Collection { id = t.First.id, name = t.Second.name, weight = t.Third.weight })
.ToList();
var todo2 = collection1.Zip(collection2, collection3)
.Select(t => new List<Collection> { t.First, t.Second, t.Third })
.First();
如果您沒有Zip回傳元組的三個引數,只需滾動您自己的引數,例如 Todo1:
var td1 = collection1.Zip(collection2, (c1, c2) => (c1, c2))
.Zip(collection3, (t12, c3) => (First: t12.c1, Second: t12.c2, Third: c3))
.Select(t => new Collection { id = t.First.id, name = t.Second.name, weight = t.Third.weight })
.ToList();
uj5u.com熱心網友回復:
我不確定您想要做什么,但要使用以下代碼獲得結果:
//TODO 1
var result1 = collection1.Where( x => new int[] { 11, 12, 13 }.ToList().Contains(x.id)).OrderBy( x => x.id).ToList();
//TODO 2
var result2 = collection1.Concat(collection2).Concat(collection3)
.Where( x => new int[] { 11, 21, 31 }.ToList().Contains(x.id)).ToList().OrderBy(x => x.id).ToList();
uj5u.com熱心網友回復:
如果您想使用 LINQ 將多個集合合并到一個集合中,請執行以下操作:
List<Collection> result = collection1.Concat(collection2).OrderBy(x => x.id).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/428901.html
下一篇:在C#中使用Linq更新現有串列
