简体   繁体   中英

C# 2 string arrays to List<string, string>

Assuming the 2 string arrays are the same length and not empty how can I make a List of the contents?

I had a Dictionary working, but now I need to be able to use duplicate keys so I am resorting to a List.

string[] files = svd.file.Split(",".ToCharArray());
string[] references = svd.references.Split(",".ToCharArray());

Dictionary<string, string> frDictionary = new Dictionary<string, string>();

frDictionary = files.Zip(rReferences, (s, i) => new { s, i })
.ToDictionary(item => item.s, item => item.i);

I could do it like:

List<string, string> jcList = new List<string, string>();

and then just have a double loop into the two arrays but I know a faster way must exist.

ILookup<string,string> myLookup = 
    files.Zip(rReferences, (s, i) => new { s, i })
         .ToLookup(item => item.s, item => item.i);

will create a Dictionary -like structure that allows multiple values per key.

So

IEnumerable<string> foo = myLookup["somestring"];

A List containing elements with two strings each is simplest implemented with a

List<T>

and

T == Tuple<string,string>

Then use a loop to build your list from the two arrays:

string[] s1 =
{
    "1", "2"
};
string[] s2 =
{
    "a", "b"
};

var jcList = new List<Tuple<string,string>>();

for (int i = 0; i < s1.Length; i++)
{
    jcList.Add(Tuple.Create(s1[i], s2[i]));
}

or using LINQ:

var jcList = s1.Select((t, i) => Tuple.Create(t, s2[i])).ToList();

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