【问题标题】:How to get Distinct elements from a List of List in c#如何从 C# 中的 List 列表中获取不同的元素
【发布时间】:2016-03-22 15:35:17
【问题描述】:

我有一个列表列表,其中子列表是字符串列表。我期待的结果是所有不同字符串的列表。 例如:

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

对于上面的列表,我期望输出为 {"A","B","C","D","E"}

这是我找到的解决方案,但我觉得它不是一个有效的解决方案。请提供您对此的想法。

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

List<string> distinctList = new List<string>();
listoflist.ForEach(list =>
{
    distinctList.AddRange(list);
});

distinctList = distinctList.Distinct().ToList();

【问题讨论】:

    标签: c# linq list


    【解决方案1】:

    您可以使用Enumerable.SelectMany 来展平列表:

    var list = listoflist.SelectMany(x => x).Distinct();
    

    如果您想具体化查询并获得List&lt;string&gt;,请添加ToList()

    【讨论】:

      【解决方案2】:

      使用SelectMany:-

      var res = listoflist.SelectMany(x => x).Distinct();
      

      SelectMany 将展平您可以应用 Distinct 方法的列表。它将返回IEnumerable&lt;string&gt;。如果您希望 List&lt;string&gt; 作为输出,则只需应用 ToList 即可实现结果:-

      List<string> distinctList = listoflist.SelectMany(x => x).Distinct().ToList();
      

      【讨论】:

        【解决方案3】:
        listofList.SelectMany().Distinct()
        

        【讨论】:

          【解决方案4】:

          这里,

          [TestClass]
          public class Class1
          {
              [TestMethod]
              public void test()
              {
                  var listoflist = new List<List<string>>
                  {
                      new List<string> {"A", "B", "C"},
                      new List<string> {"A", "B", "D", "E"}
                  };
                  var result = listoflist.SelectMany(l=>l).Distinct().ToList();
                  Assert.AreEqual(result.Count, 5);
              }
          }
          

          【讨论】:

            【解决方案5】:

            我会用,

            var distinctValues= listoflist[0].Concat(listoflist[1]).GroupBy(a=&gt;a).Select(x =&gt; x.First());

            这里,first 将选择第一条记录,groupBy 将分组相同的值

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-12-09
              • 1970-01-01
              • 2020-09-11
              • 1970-01-01
              • 2012-07-30
              相关资源
              最近更新 更多