0

我有以下列表:

List<string> l1 = new List<string> { "A4,A2","A1,A3" };
List<string> l2 = new List<string> { "A5,A6", "A7,A8" };

我需要将这两个结合起来并创建一个列表,其中包含用逗号分隔的所有项目,所以我最终应该包含以下内容:

A4,A2,A1,A3,A5,A6,A7,A8,A9

我使用以下内容来组合这两个列表:

string s1 = string.Join(",", l1.ToArray());
string s2 = string.Join(",", l2.ToArray());

var combinedItems = s1 + "," + s2;

然后我需要将结果与另一个列表进行比较,以确保它包含从 A1 到 A8 的元素

var allItems = new List<string> { "A1,A2,A3,A4,A5,A6,A7,A8" };

bool allItemsExist = allItems.Any(combinedItems.Contains);

这失败了,因为combineItems变量的排序与allItems排序不匹配。

如何对 combineItems 的内容进行排序,或者是否有另一种方法可以实现我想要实现的目标?

4

5 回答 5

2
var items = new[] { l1, l2 }
            .SelectMany(x => x.SelectMany(y => y.Split(',')))
            .OrderBy(y => y);

var allItems = new List<string> 
                        { "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8" };

var result = allItems.SequenceEqual(items);
于 2013-06-20T11:24:49.270 回答
1

粗鲁的解决方案:

      List<string> l1 = new List<string> { "A4,A2", "A1,A3" };
      List<string> l2 = new List<string> { "A5,A6", "A7,A8" };

      var s1 = string.Join(",", l1.ToArray());
      var s2 = string.Join(",", l2.ToArray());

      var combinedItems = s1 + "," + s2;
      var splittedAndOrderedCombinedItems = combinedItems.Split(',').OrderBy(x => x).ToList();

      var allItems = new List<string> { "A1,A2,A3,A4,A5,A6,A7,A8" };
      var firstOrDefault = allItems.FirstOrDefault();

      var splittedAllItems = new List<string>();
      if (firstOrDefault != null) {
        splittedAllItems = firstOrDefault.Split(',').ToList();
      }

      var result = splittedAllItems.Any(splittedAndOrderedCombinedItems.Contains);
于 2013-06-20T11:14:40.517 回答
0

又快又脏:

        var allItemsList = allItems.First().Split(',').ToList();
        var combinedItemsList = combinedItems.Split(',').ToList();

        bool allItemsExists = combinedItemsList.All(x => allItemsList.Contains(x)); 

将逗号分隔的字符串保存为列表中的一项是没有意义的,因此请从中创建一个 REAL 列表。

我的最后一条语句确定是否每个项目 (A1-A8) 都包含在 allItemsList 中。

PS:在我的测试中allItemsExists返回。true

于 2013-06-20T11:10:54.370 回答
0

您可以拆分所有项目:

List<string> l1 = new List<string> { "A4,A2", "A1,A3" }.SelectMany(x => x.Split(',')).ToList();
List<string> l2 = new List<string> { "A5,A6", "A7,A8" }.SelectMany(x => x.Split(',')).ToList();

string combinedItems = string.Join(",", l1.Concat(l2));

List<string> allItems = new List<string> { "A1,A2,A3,A4,A5,A6,A7,A8" }.SelectMany(x => x.Split(',')).ToList();

bool allItemsExist = allItems.All(combinedItems.Contains);
于 2013-06-20T11:11:08.007 回答
0

将所有字符串拆分为“A1”“A2”部分,对它们进行排序并加入它们。

    List<string> l1 = new List<string> { "A4,A2", "A1,A3" };
    List<string> l2 = new List<string> { "A5,A6", "A7,A8" };
    var result = l1.SelectMany(x => x.Split(',')).Union(l2.SelectMany(x => x.Split(','))).OrderBy(x => x).ToList();
    var str = string.Join("," , result);
    str.Dump();

输出:

A1,A2,A3,A4,A5,A6,A7,A8
于 2013-06-20T11:14:35.240 回答