【问题标题】:C# 2 string arrays to List<string, string>C# 2 字符串数组到 List<string, string>
【发布时间】:2014-12-17 15:50:02
【问题描述】:

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

然后对两个数组进行双循环,但我知道必须存在更快的方法。

【问题讨论】:

  • ",".ToCharArray() == ','
  • 如果你开始编写自己的类型(列表没有字符串,字符串重载。)你还不如创建自己的类来保存数据。
  • 你不能有List&lt;string, string&gt;
  • 可能是列表>?不要认为唯一键有限制,但可能是错误的。
  • Pete 如果你想使用等同于List&lt;string, string&gt; 的东西,那么你可以使用Immutable Struct C# SO Immutable Struct List<string,string>

标签: c#


【解决方案1】:
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"];

【讨论】:

    【解决方案2】:

    一个包含两个字符串元素的列表最简单的实现是用 a

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

    【讨论】:

    • 只有代码,OP 无法理解您在做什么。向其中添加一些文档
    • -1 LOL 我完全同意VDesign 哇,我认为我不会这么想我的猫。对不起
    • 仅供参考,您可以使用new Tuple&lt;string, string&gt;(s1[i], s2[i]) Tuple.Create(s1[i], s2[i])
    • 请注意:使用spender's Lookup,任何搜索都将比使用这个简单的扁平列表快(很多)
    猜你喜欢
    • 2012-10-04
    • 2013-11-03
    • 2021-02-23
    • 2013-08-28
    • 2012-12-26
    • 1970-01-01
    • 2012-04-06
    • 2011-04-04
    相关资源
    最近更新 更多