您好我有从一个列表中的项目,以anothers分配属性值的一个小问题。我知道我可以通过这两个列表迭代等解决它的老办法,但我使用LINQ寻找更优雅的解决方案。
Hello I have a little problem with assigning property values from one lists items to anothers. I know i could solve it "the old way" by iterating through both lists etc. but I am looking for more elegant solution using LINQ.
让我们先从代码。 ..
Let's start with the code ...
class SourceType { public int Id; public string Name; // other properties } class DestinationType { public int Id; public string Name; // other properties } List<SourceType> sourceList = new List<SourceType>(); sourceList.Add(new SourceType { Id = 1, Name = "1111" }); sourceList.Add(new SourceType { Id = 2, Name = "2222" }); sourceList.Add(new SourceType { Id = 3, Name = "3333" }); sourceList.Add(new SourceType { Id = 5, Name = "5555" }); List<DestinationType> destinationList = new List<DestinationType>(); destinationList.Add(new DestinationType { Id = 1, Name = null }); destinationList.Add(new DestinationType { Id = 2, Name = null }); destinationList.Add(new DestinationType { Id = 3, Name = null }); destinationList.Add(new DestinationType { Id = 4, Name = null });
我想实现以下内容:
I would like to achieve the following:
- DESTINATIONLIST应充满在SOURCELIST相应的条目(凭身份证)
- DESTINATIONLIST不应包含不存在于两个列表一次条目的名称(如:编号:4,5应该被淘汰) - 像内部联接
- 我想,以避免与更新的条目创建新DESTINATIONLIST因为这两个名单已经存在并且是非常大的,所以没有转换或选择新的
在年底DESTINATIONLIST应包含以下内容:
In the end destinationList should contain:
1 "1111" 2 "2222" 3 "3333"是否有某种优雅(一行LAMBDA;?)?解决这个使用LINQ
Is there some kind of elegant (one line Lambda? ;) solution to this using LINQ ?
任何帮助将不胜感激! !谢谢
Any help will be greatly appreciated! Thanks!
推荐答案我只是想建立一个字典,并使用:
I would just build up a dictionary and use that:
Dictionary<int, string> map = sourceList.ToDictionary(x => x.Id, x => x.Name); foreach (var item in destinationList) if (map.ContainsKey(item.Id)) item.Name = map[item.Id]; destinationList.RemoveAll(x=> x.Name == null);更多推荐
分配从一个列表值到另一个使用LINQ
发布评论