C# 2 字符串数组到列表<字符串,字符串>

本文关键字:字符串 列表 数组 | 更新日期: 2023-09-27 18:34:33

>假设 2 个字符串数组的长度相同且不为空,如何制作内容列表?

我有一个字典在工作,但现在我需要能够使用重复的键,所以我求助于列表。

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

我可以这样做:

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

然后只是在两个数组中有一个双循环,但我知道必须存在更快的方法。

C# 2 字符串数组到列表<字符串,字符串>

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

将创建一个类似Dictionary的结构,该结构允许每个键有多个值。

所以

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

包含元素的列表,每个元素有两个字符串,最简单的方法是使用

List<T>

T == Tuple<string,string>

然后使用循环从两个数组构建列表:

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]));
}

或使用 LINQ:

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