我有以下列表:
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);
此操作失败,因为 combinedItems 变量的排序与 allItems 排序不匹配。
如何对 combinedItems 的内容进行排序,还是有其他方法可以实现我想要实现的目标?
答案 0 :(得分: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);
答案 1 :(得分:1)
brut解决方案:
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);
答案 2 :(得分:0)
快速而肮脏:
var allItemsList = allItems.First().Split(',').ToList();
var combinedItemsList = combinedItems.Split(',').ToList();
bool allItemsExists = combinedItemsList.All(x => allItemsList.Contains(x));
将逗号分隔的字符串保存为列表中的一个项是没有意义的,因此请从中创建一个REAL列表。
我的上一个语句确定是否每个Item(A1-A8)都包含在allItemsList中。
PS:allItemsExists
在我的测试中返回true
。
答案 3 :(得分: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);
答案 4 :(得分: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