简体   繁体   中英

C# Making a new list by combining two lists together

So I am trying to find how to best make a list that will combine two lists of equal size of two different types together, in a way so that the indexes will be the same. How can i do this?

var list = new List<KeyValuePair<List<Card>, List<Card>>>();
list.AddRange(new List<KeyValuePair<List<Card>,List<Card>>>(_listCards,cloneOf_listCards));

The code above has been my way of trying to get it to work where Card is a class with both Suit and Cardnumber. though my code doesn't do it i wish to make it a list with Images instead of Card for one list. I have already seen these and many other threads: join of two lists in c# https://stackoverflow.com/questions/16465804/return-two-combined-listt

You could use the Enumerable.Zip extension method.

For example:

_listCards.Zip(cloneOf_listCards, (cardA, cardB) => new KeyValuePair<Card, Card>(cardA, cardB));

Granted, this will give you a single List<KeyValuePair<Card,Card>> instead of a KeyValuePair<List<Card>, List<Card>> , but I'd argue that's a better design anyways.

At that point (if you so desire), you can probably just turn it into a Dictionary<Card,Card> :

var joined = _listCards.Zip(cloneOf_listCards, (cardA, cardB) => new KeyValuePair<Card, Card>(cardA, cardB));
var dictionary = joined.ToDictionary(kv => kv.Key, kv => kv.Value);

Note that if your lists are of different sizes, Enumerable.Zip will only join the elements up to the end of the shorter list and then stop.

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