简体   繁体   中英

Need help joining two lists of objects in C#

With my two lists of objects, I want to keep the total set of unique items based on a string key, where any collisions come from the first list, and any misses come from the second. Stated differently, I want to ignore any items in the first list that are not in the second list, but I want to keep all items that do exist in the second list as well as any remaining items from the second list.

What's the best way to do this?

Edit: This problem is more subtle than a simple union. A union will join the distinct items from two lists. In the case of a collision it takes the item from the outer list.

In my case, I have some items in List1 that I don't want to keep because they don't exist in List2, while I do want to keep all items from list 2.

Is there a cleaner / shorter way to do the below?

var remaining = allowedItems.Except(recentItems)
var allowedRecentItems = recentItems.Intersect(allowedItems)
var result = allowedRecentItems.Concat(remaining);

尝试这个:

var resultlist = list1.Union(list2);
var list1 = new List<string>{"A", "B", "C"};
var list2 = new List<string>{"B", "C", "D"};
var list = list1.Union(list2);

Using the second list just do the trick. Directly translating your your requirements produces: list1.Intersect(list2).Union(list2) which results list2

If I understood it correctly - You should keep the second list only. By that your both conditions are fulfilled

  • I want to ignore any items in the first list that are not in the second list

off-course if you keep the second list only then all the items in the first list which are not present in the second list will automatically be ignored.

  • I want to keep all items that do exist in the second list as well as any remaining items from the second list

On the other hand, the items present in both of the lists will automatically be selected including those which are only present in the second list.

If that's not what you want then you should check List.Distinct() , List.Except() and List.Union() extension methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM