分配从一个列表值到另一个使用LINQ

编程入门 行业动态 更新时间:2024-10-10 07:21:22
本文介绍了分配从一个列表值到另一个使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您好我有从一个列表中的项目,以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

本文发布于:2023-11-05 02:44:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   列表   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!