C# 使用Linq同时更新可观察集合项的两个字段
我有两个相同类型的可观察收集列表:C# 使用Linq同时更新可观察集合项的两个字段,c#,linq,visual-studio-2008,.net-3.5,C#,Linq,Visual Studio 2008,.net 3.5,我有两个相同类型的可观察收集列表: ObservableCollection<MyDataModel> source; ObservableCollection<MyDataModel> target; 我的模型: public class MyDataModel { public int Id { get; set; } public string Desc { get; set; } public string Country { get;
ObservableCollection<MyDataModel> source;
ObservableCollection<MyDataModel> target;
我的模型:
public class MyDataModel
{
public int Id { get; set; }
public string Desc { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
在上面的例子中,我重复了目标。前两次,我想避免这一点,并立即这样做。是否可以使用Linq?您只需执行一次
First()
,然后将结果分配给一个变量
foreach (var s in source)
{
var item = target.First(t => t.Id == s.Id);
item.Id = s.Id;
item.Desc = s.Desc;
}
此外,由于查找项目的标准是Id是否匹配,因此实际上不需要item.Id=s.Id代码>步骤
编辑
但是,如果在目标中找不到该项,则上述代码有引发异常的风险。这将是一个更好的方法:
foreach (var s in source)
{
var item = target.Where(t => t.Id == s.Id).FirstOrDefault();
if (item != null)
{
item.Id = s.Id;
item.Desc = s.Desc;
}
}
简单回答:
foreach (var s in source)
{
var t = target.First(x => x.Id == s.Id);
t.Desc = s.Desc;
t.Country = s.Country;
}
简单的答案是O(源*目标)操作。通过使用字典,可以将性能提高到O(源+目标):
var sourceDict = source.ToDictionary(s => s.Id);
foreach (var t in target)
{
MyDataModel s;
if (sourceDict.TryGetValue(t.Id, out s))
{
t.Desc = s.Desc;
t.Country = s.Country;
}
}
为什么您不能只var current=target.First(t=>t.Id==s.Id)
然后用当前的做任何你想做的事
?哦@Federico在评论中击败了我。
var sourceDict = source.ToDictionary(s => s.Id);
foreach (var t in target)
{
MyDataModel s;
if (sourceDict.TryGetValue(t.Id, out s))
{
t.Desc = s.Desc;
t.Country = s.Country;
}
}