我有一个设想
class a
{
String Username;
String val;
}
List<a> lst = new List<a>();
List<a> lstnew = new List<a>();
我需要的是 lstnew
我在 val
属性 (Only in Several Objects) 中有一些更新的值,我需要的是使用 LINQ
lstnew
中的更新值更新 lst
作为 Username
属性
最佳答案
您可以在 UserName
上加入两个列表,然后用第二个列表中的值更新第一个列表中的 Value
。
例如,给定这个类和列表:
public class a
{
public string UserName { get; set; }
public string Value { get; set; }
}
List<a> list = new List<a>
{
new a { UserName = "Perry", Value = "A" },
new a { UserName = "Ferb", Value = "B" },
new a { UserName = "Phineas", Value = "C" }
};
List<a> newList = new List<a>
{
new a { UserName = "Phineas", Value = "X" },
new a { UserName = "Ferb", Value = "Y" },
new a { UserName = "Candace", Value = "Z" }
};
您可以加入以获取具有共同UserName
的元素:
var common = from a1 in list
join a2 in newList on a1.UserName equals a2.UserName
select new { A1 = a1, A2 = a2 };
此时,如果我没理解错的话,你想更新原始列表中的元素:
foreach(var c in common)
{
c.A1.Value = c.A2.Value;
}
此时 list
中的元素看起来像:
UserName Value
-----------------
Perry A
Ferb Y
Phineas X
关于c# - 使用 LINQ 将一个对象属性列表更新为其他列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8599644/