简体   繁体   English

比较两个长度不同的字符串列表,以根据内容而不是长度进行区别

[英]Compare two lists of strings of varying length for difference based on content, not length

I have two lists, imported and existing . 我有两个列表, importedexisting They can be of the same length, or of different length. 它们的长度可以相同,也可以不同。

I want to check if there's anything in imported that's not in existing . 我要检查,如果有什么事,在imported ,这不是在existing

If they're the same length, I'm able to compare them and find a mismatch with the following: 如果它们的长度相同,我可以将它们进行比较,并找到与以下内容不匹配的内容:

if(Enumerable.SequenceEqual(imported.OrderBy(i => i), existing.OrderBy(ex => ex)) == false)

If the lists are the same length, the above works as expected. 如果列表的长度相同,则以上内容将按预期工作。 If not, it doesn't as one contains items the other doesn't, which makes sense. 如果没有,它就不会包含一个项目,而另一个则不会。

How can I do this for lists of different lengths? 如何针对不同长度的列表执行此操作?

Scenario A , should pass, there's nothing in imported that's not in existing : 方案A应该通过, imported中没有不existing

Existing: "One", "Two", "Three" 现有: "One", "Two", "Three"

Imported: "One","Two" 导入: "One","Two"

Scenario B , should fail, "Two" is in imported but it's not in existing : 方案B ,应该失败, imported “ Two”,但不existing

Existing: "One", "Two", "Three" 现有: "One", "Two", "Three"

Imported: "One","Tow" 导入: "One","Tow"

I've used Intersect , Except and Any but they will work on Scenario A and not B, or vice versa. 我已经使用了IntersectExceptAny但是它们将在方案A而非B上工作,反之亦然。

imported.Except(existing).Any();

Enumerable.Except could be your tool 可枚举。可能是您的工具

List<string> imported = new List<string>() {"One", "Two", "Three"};
List<string> existing = new List<string>() {"One", "Two", "Four"};

List<string>missing = imported.Except(existing, 
                      StringComparer.CurrentCultureIgnoreCase).ToList();
if(missing.Count == 0)
    Console.WriteLine("Nothing to import");
else
    Console.WriteLine("There are " + missing.Count + " items to import");

Of course, this answer assumes that you have something to do with the resulting difference (if any). 当然,此答案假定您与所产生的差异(如果有)有关。 Otherwise the asnwers using Any are more direct to you question 否则,使用Any的提升者会更直接地向您提问

这可能会有所帮助:

imported.Any(i=>!existing.Contains(i));
if (imported.Any(item => !existing.Contains(item)))
    ...

通过填充null或字符串使两个列表具有相同的长度怎么办?清空缺少的位置?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM