Merge two list objects

I have a problem with combining two lists of objects, here they are:

first one List<NSKData> NSKDataList = new List<NSKData>(); public class NSKData { public string ID { get; set; } public string Issue { get; set; } public string ToolTipInfoText { get; set; } public NSKData() { } public NSKData(string id, string issue, string tooltipinfo) { ID = id; Issue= issue; ToolTipInfoText = tooltipinfo; } } second one List<IssuesMoreInfo> IssuesMoreInfoList = new List<IssuesMoreInfo>(); public class IssuesMoreInfo { public string ID { get; set; } public string IssueMoreInfoText { get; set; } } 

If I can get all the necessary data at one time, I will not ask this question, but I grab all the data for a fist, and only after I get the data for the second.

So, what do I need as a result: to get IssueMoreInfo from the second, according to the identifier in both, as well as for the identifier 10 in the first, we get the IssueMoreInfoText column in the second and pass it to one list in the ToolTipInfoText column

Hope for your help guys thanks

+5
source share
3 answers

I assume you are looking for Enumerable.Join :

 var query = from data in NSKDataList join info in IssuesMoreInfoList on data.ID equals info.ID select new NSKData(data.ID, data.Issue, info.IssueMoreInfoText); NSKDataList = query.ToList(); 

Another way that does not require re-creating all objects and the list:

 var infoIdLookup = IssuesMoreInfoList.ToLookup(i => i.ID); foreach(NSKData data in NSKDataList) { data.ToolTipInfoText = infoIdLookup[data.ID] .Select(i => i.IssueMoreInfoText) .FirstOrDefault(); } 
+4
source

Try using Linq Join

 var query = from c in NSKDataList join o in IssuesMoreInfoList on c.ID equals o.ID select new { c.ID, c.Issues , c.ToolTipInfoText , o.IssueMoreInfo }; 

The request will contain information from both lists.

http://www.dotnetperls.com/join

+2
source

To use Linq, it’s easier to do:

 NSKDataList.ForEach(nskData => nskData.ToolTipInfoText = IssuesMoreInfoList.Where(imf => imf.ID == nskData.ID).SingleOrDefault().IssueMoreInfoText); 

What does he do:

The Foreach element in NSKDataList will change its ToolTipInfoText when you go to IssuesMoreInfoList and filter it by ID by request, and then get the one that was returned or the default (if none were selected) and get it IssueMoreInfoText .

0
source

Source: https://habr.com/ru/post/1240149/


All Articles