簡體   English   中英

如何檢查是否列表<string>存在其他列表中的所有值<string></string></string>

[英]how to check if List<string> exists all values in other List<string>

我試圖弄清楚如何檢查所有值是否與其他列表值匹配。

例子:

List<string> foo = new List<string>() {"banana","apple","coconut"}
List<string> bar = new List<string>() {"banana","apple","coconut","mango", "lemon"}

如果每個 foo 列表項都存在於 bar 中,則返回 true,如果至少有一個不在 foo 列表中,則返回 false。 並且如果示例:

List<string> foo = new List<string>() {"banana",}
List<string> bar = new List<string>() {"banana","apple","coconut","mango", "lemon"}

應該返回真

並且如果示例:

List<string> foo = new List<string>() {"banana","melon"}
List<string> bar = new List<string>() {"banana","apple","coconut","mango", "lemon"}

應該返回 false

並且如果示例:

List<string> foo = new List<string>() {"banana","apple","coconut","mango", "lemon"}
List<string> bar = new List<string>() {"banana"}

應該返回 false

對不起所有的變化。 得快點做:D

在你的情況下,我認為你可以使用類似的東西

 var resultBool = foo.All(x => bar.Any(y => x == y));

在這里,我們按每個值比較列表。 如果 foo 的字符串值不在 bar 中,則結果將為 false。

我認為這將幫助您找到解決方案。

List<string> foo = new List<string>() { "banana", "apple", "coconut" };
List<string> bar = new List<string>() { "banana", "apple", "coconut", "mango", "lemon" };
//true
var test1 = foo.All(x => bar.Any(y => x == y));

List<string> foo2 = new List<string>() { "banana", };
List<string> bar2 = new List<string>() { "banana", "apple", "coconut", "mango", "lemon" };
//true
var test2 = foo2.All(x => bar2.Any(y => x == y));

List<string> foo3 = new List<string>() { "banana", "melon" };
List<string> bar3 = new List<string>() { "banana", "apple", "coconut", "mango", "lemon" };
//false
var test3 = foo3.All(x => bar3.Any(y => x == y));

List<string> foo4 = new List<string>() { "banana", "apple", "coconut", "mango", "lemon" };
List<string> bar4 = new List<string>() { "banana" };
//false
var test4 = foo4.All(x => bar4.Any(y => x == y));

快樂的編碼:)

這實際上使用Intersect()非常簡單

foo.Intersect(bar).Count() == foo.Count()

嘗試Except

var matching = !foo.Except(bar).ToList().Any();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM