我有這個物件串列,其中包含具有元組 listProducts 的物件串列:(區域變數)List<((string GroupName, string Valeurs)[] Levels, string[] Uids)>分組
[{
"Item1": [{
"Item1": "coloris",
"Item2": "Beige"
}, {
"Item1": "ref_commercial",
"Item2": "29245"
}],
"Item2": ["QB32-20220325-486274", "QB32-20220325-106045"]
}, {
"Item1": [{
"Item1": "coloris",
"Item2": "Venezia"
}, {
"Item1": "ref_commercial",
"Item2": "29245"
}],
"Item2": ["QB32-20220325-205994", "QB32-20220325-270903"]
}]
ListOfIds =["QB32-20220325-486274", "QB32-20220325-106045", "QB32-20220325-205994", "QB32-20220325-270903"]
我想遍歷 id 串列并檢查 listProducts 上是否存在,如果存在則從 Item2 中洗掉它。
所以最后 Item2 在這種情況下將包含一個空串列。
uj5u.com熱心網友回復:
回圈遍歷主串列,然后檢查 item2 串列是否包含 id 并將其洗掉。
foreach(var id in ListOfIds)
{
foreach( var item in groupings)
{
if (item.Uids.Contains(id))
{
item.Uids.Remove(id);
}
}
}
uj5u.com熱心網友回復:
鑒于這ValueTuple是一種存盤需要修改的資訊的糟糕方式(創建一個類,或者如果必須使用匿名類),并且鑒于 C# 陣列不應該用于必須修改的集合(使用 a List<T>),這里是一些代碼來替換List<T>必須修改的元素:
var listOfIds = new[] { "QB32-20220325-486274", "QB32-20220325-106045", "QB32-20220325-205994", "QB32-20220325-270903" }.ToHashSet();
for (int productIndex = 0; productIndex < listProducts.Count; productIndex) {
var product = listProducts[productIndex];
product.Uids = product.Uids.Where(uid => !listOfIds.Contains(uid)).ToArray();
listProducts[productIndex] = product;
}
uj5u.com熱心網友回復:
for使用類似或foreach導致錯誤的“經典回圈” Cannot modify struct member when accessed struct is not classified as a variable。發生這種情況是因為元組是結構,當在 a 內部訪問時foreach,for您將結束訪問此變數的副本,而不是變數本身。
但是您可以使用 LINQ 輕松地做到這一點
listProducts = listProducts.Select(x =>
{
x.Uids = x.Uids.Except(ListOfIds).ToArray();
return x;
}).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457172.html
