【问题标题】:How To Compare 2 lists of Strings using for each如何使用 for 比较 2 个字符串列表
【发布时间】:2014-09-27 02:21:54
【问题描述】:

我正在尝试使用此代码遍历 2 个列表

foreach (string str1 in list<string>tags)
{ 
    foreach (string str2 in list<string>ArchivedInformation) { }
}

第一个列表的标签存储为“tag1, tag2,tag3..”,第二个列表的信息存储为“tag1, Datestamp, 0.01”,"tag2, datestamp, 0.02" 等等。

我想问我如何才能获得第二个列表中的标签并将其用作我的第一个条件?我尝试拆分第二个列表,但我无法获得确切的“Tag1”作为 id 以将其用作条件。

最后我想做的目标是Str1(from tags list) == Str2(From Archivedinformation)

【问题讨论】:

  • 您考虑过使用字典吗?
  • 我没有,谢谢你的建议。
  • 只是想知道,仅使用字典是否可行?或者也可以使用列表来完成
  • 你熟悉字典吗?它是一个包含键和相关值列表的数据结构。我会构建您的数据,以便标签是字典键,而 ArchivedInformation 值是字典值。您不需要在值中包含标签,因此它就像“日期戳,0.01”。您可以使用 Dictionary>。不过,我不确定我是否了解您实际上想用 foreach 循环做什么。您似乎只是在尝试关联数据,如果您不使用两个列表,您甚至可能不需要。
  • 是的,我实际上是同时访问 2 个列表,因为它是系统的当前设计。但绝对是一本字典,我需要查看它,只是他们的偏好是访问 2 个列表并比较它们的 id。非常感谢!

标签: c#


【解决方案1】:

一切皆有可能。另一件事是,如果它甚至是理智的:)

    public void Something()
    {
        // Using Dictionary
        var dict = new Dictionary<string, string>();
        dict.Add("tag1", "tag1,datestamp,0.01");
        dict.Add("tag2", "tag2,datestamp,0.02");

        // out -> "tag2,datestamp,0.02"            
        System.Diagnostics.Debug.WriteLine(dict["tag2"]);    


        // Using two separate lists
        var tags = new List<string> { "tag1", "tag2" };
        var infos = new List<string> { "tag1,datestamp,0.01", "tag2,datestamp,0.02" };

        // out ->  tag1,datestamp,0.01 & tag2,datestamp,0.02
        tags.ForEach(tag =>
            System.Diagnostics.Debug.WriteLine(
                infos.First(info => info.StartsWith(tag)))); 
    }

【讨论】:

  • 谢谢!我也尝试使用此功能 string cmp; cmp = str2.Substring(0,str2.IndexOf(','));
猜你喜欢
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
相关资源
最近更新 更多