0

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.

7
  • ",".ToCharArray() == ',' Commented Dec 17, 2014 at 15:51
  • If you are starting to make up your own types (list doesnt have a string, string overload.) You might as well just make your own class with properties to hold the data. Commented Dec 17, 2014 at 15:53
  • 1
    You can't have List<string, string>. Commented Dec 17, 2014 at 15:54
  • Maybe List<KeyValuePair<string, string>>? Don't think there is a restriction on unique key, but could be wrong. Commented Dec 17, 2014 at 15:55
  • Pete if you want to use something that would be equivalent to List<string, string> then you can use an Immutable Struct C# SO Immutable Struct List<string,string> Commented Dec 17, 2014 at 15:57

2 Answers 2

12
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"];
Sign up to request clarification or add additional context in comments.

Comments

0

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();

4 Comments

with just code the OP can't understand what you are doing. Add some documentation to it
-1 LOL I totally agree VDesign wow talk about over thinking in my opinion I would not skin my cat this way.. sorry
FYI instad of new Tuple<string, string>(s1[i], s2[i]) you can use Tuple.Create(s1[i], s2[i]).
please note: with spender's Lookup any search will be (much) faster than with this simple flat List

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.