我有一個物件串列 =>class Example { int quantity; string name; string comment; }并且我想洗掉所有重復項并增加quantity具有相同name和的重復項數comment。
例子:
[
{quantity: 1, name: "Hello", comment: "Hello there"},
{quantity: 2, name: "Bye", comment: "Good bye"},
{quantity: 1, name: "Hi", comment: "Hi there"},
{quantity: 1, name: "Hello", comment: "Hello there"},
{quantity: 1, name: "Bye", comment: "Good bye"},
]
結果應該是:
[
{quantity: 2, name: "Hello", comment: "Hello there"},
{quantity: 3, name: "Bye", comment: "Good bye"},
{quantity: 1, name: "Hi", comment: "Hi there"}
]
uj5u.com熱心網友回復:
我想洗掉所有重復項
您尚未定義何時兩個示例物件是“重復的”。我猜,您的意思是說,如果兩個 Example 物件具有相同的屬性值Name和Comment,則它們是重復的。
通常,您可以使用
或許這個版本更清晰一點:
Example[] after =
before
.GroupBy(
x => new { x.Name, x.Comment },
(k, xs) => new Example
{
Quantity = xs.Sum(x => x.Quantity),
Name = k.Name,
Comment = k.Comment
})
.ToArray();
或者這個:
Example[] after =
(
from x in before
group x.Quantity by new { x.Name, x.Comment } into xs
select new Example
{
Quantity = xs.Sum(x => x),
Name = xs.Key.Name,
Comment = xs.Key.Comment
}
).ToArray();
uj5u.com熱心網友回復:
這是一個簡單的解決方案,它在 List tata 中為您提供答案,但如果您愿意,您可以執行 .ToArray() 。
public class Example
{
public int quantity;
public string name;
public string comment;
}
Example[] toto = new Example[]
{
new Example
{
quantity = 1,
name = "Hello",
comment = "Hello there"
},
new Example
{
quantity = 2,
name = "Bye",
comment = "Good bye"
},
new Example
{
quantity = 1,
name = "Hi",
comment = "Hi there"
},
new Example
{
quantity = 1,
name = "Hello",
comment = "Hello there"
},
new Example
{
quantity = 1,
name = "Bye",
comment = "Good bye"
}
};
List<Example> tata = new List<Example>();
foreach (Example exa in toto)
{
bool found = false;
foreach (Example exb in tata)
{
if (exb.name == exa.name && exb.comment == exa.comment)
{
exb.quantity = exa.quantity;
found = true;
break;
}
}
if (!found)
{
tata.Add(exa);
}
}
一個很好的練習是 LINQ!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381800.html
下一篇:LINQ:如何獲取1個月的記錄
