使用 LINQ 比较两个列表

发布于 2024-11-06 13:07:54 字数 557 浏览 0 评论 0原文

如果我有 2 个字符串列表:

List<string> firstList = new List<string>("010", "111", "123");
List<string> secondList = new List<string>("010", "111", "999");

如何比较列表中每个项目中的每个单独字符?例如:应该比较“0”与“0”,“1”与“1”,“0”与“0”等。看来我可以使用 SelectMany 但我坚持如何去做

编辑:

这些列表在相互比较时应该返回 true (因为星号表示任何字符,我正在验证以确保每个项目长度正好是 3 个字符)

List<string> firstList = new List<string>("010", "111", "123");
List<string> secondList = new List<string>("010", "1*1", "***");

If I have 2 lists of strings:

List<string> firstList = new List<string>("010", "111", "123");
List<string> secondList = new List<string>("010", "111", "999");

How can I compare each individual character in each item from the lists? Ex: Should compare "0" with "0", "1" with "1", "0" with "0" and so on. It appears that I can use SelectMany but I am stuck on how to do it

EDIT:

These lists should return true when compared with each other (as asterisk means any character and I am validating to ensure that each item is exactly 3 chars in length)

List<string> firstList = new List<string>("010", "111", "123");
List<string> secondList = new List<string>("010", "1*1", "***");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

似梦非梦 2024-11-13 13:07:54

使用通配符更新

class WildcardStringComparer : IEqualityComparer<string>
{
    public bool Equals(string s1, string s2)
    {
        if (s1.Length != s2.Length) return false;

        for (int i = 0; i < s1.Length; i++)
        {
            if (s1[i] != s2[i] && s1[i] != '*' && s2[i] != '*')
                return false;
        }

        return true;
    }


    public int GetHashCode(string obj)
    {
        throw new NotImplementedException();
    }
}

结果:

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "999"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // True

and

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "*99"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // True

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "199"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // False

Updated with wildcards

class WildcardStringComparer : IEqualityComparer<string>
{
    public bool Equals(string s1, string s2)
    {
        if (s1.Length != s2.Length) return false;

        for (int i = 0; i < s1.Length; i++)
        {
            if (s1[i] != s2[i] && s1[i] != '*' && s2[i] != '*')
                return false;
        }

        return true;
    }


    public int GetHashCode(string obj)
    {
        throw new NotImplementedException();
    }
}

Results:

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "999"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // True

and

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "*99"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // True

and

List<string> firstList = new List<string>{"010", "111", "999"};
List<string> secondList = new List<string>{"010", "111", "199"};

bool res = firstList.SequenceEqual(secondList, new WildcardStringComparer()); // False
瀟灑尐姊 2024-11-13 13:07:54

如果您只想比较列表之间的匹配字符序列:

bool sameCharacters = Enumerable.SequenceEqual(firstList.SelectMany(x => x), 
                                               secondList.SelectMany(x => x));

这将导致 true,即对于以下两个列表 - 它们的字符序列匹配 ("010111123"对于两者),它们各自的字符串条目不会:

List<string> firstList = new List<string> {"010", "111", "123" };
List<string> secondList = new List<string> {"010", "11", "1123" };

编辑以响应注释:

对于通配符匹配,您可以使用 Zip() 并比较每个字符,如果满足则返回 true根据通配符条件进行匹配,然后检查压缩序列中的每个元素都是true

var isWildCardMatch = firstList.SelectMany(x => x).Zip(secondList.SelectMany( x => x),
(a,b)=>
{
if(a==b || a =='' || b == '')
返回真;
return false;

    }).All( x=> x);

上述方法跨越了字符串条目边界,这会导致错误匹配 - 这里有一个更好的方法:

bool isWildCardMatch = firstList.Zip(secondList, (x, y) =>
{
    var matchWord = y.Select((c, i) => c == '*' ? x[i] : c);
    return matchWord.SequenceEqual(x);
}).All(x => x);

If you just want to compare for a matching character sequence between your lists:

bool sameCharacters = Enumerable.SequenceEqual(firstList.SelectMany(x => x), 
                                               secondList.SelectMany(x => x));

This would result in true, i.e. for the following two lists - their character sequences match ("010111123" for both), their individual string entries do not:

List<string> firstList = new List<string> {"010", "111", "123" };
List<string> secondList = new List<string> {"010", "11", "1123" };

Edit in response to comments:

For a wildcard match you could use Zip() and compare each character, return true if they match based on wildcard conditions, then just check that each element in the zipped sequence is true.

var isWildCardMatch = firstList.SelectMany(x => x).Zip(secondList.SelectMany( x => x),
(a,b) =>
{
if(a==b || a =='' || b == '')
return true;
return false;

    }).All( x=> x);

Above approach crossed string entry boundaries, which would cause false matches - here a better approach:

bool isWildCardMatch = firstList.Zip(secondList, (x, y) =>
{
    var matchWord = y.Select((c, i) => c == '*' ? x[i] : c);
    return matchWord.SequenceEqual(x);
}).All(x => x);
谎言 2024-11-13 13:07:54

假设您要将第一个列表中第一个字符串的第一个字符与第二个列表中第一个字符串的第一个字符进行比较,第一个列表中第一个字符串的第二个字符与第二个列表中第一个字符串的第二个字符进行比较第二个列表等。我可以想到两种实现。

我将从以下开始:

var firstCharList = new List<char>();
var secondCharList = new List<char>();

firstList.foreach(s => 
 {
   foreach(char c in s)
   {
      firstCharList.Add(c);
   }
  });

secondList.foreach(s =>
{
   foreach(char c in s)
   {
      secondCharList.Add(c);
   }
});

for(int i = 0; i < firstCharList.Length; i++)
{
   if(firstCharList[i] == secondCharList[i]) yield return i;
}

这将生成一个整数列表(或数组,或其他),这些整数对应于两个字符串具有相同字符的索引。

第二个是这样的:

firstList.foreach(s =>
{
   var index = firstList.IndexOf(s);
   var sPrime = secondList[index];
   for(int i = 0; i < s.Length; i++)
   {
      if(s[i] == sPrime[i]) yield return s[i];
   }
}

那个只返回在相同索引处相等的任何字符。

Assuming you want to compare the first character of the first string in the first list to the first character of the first string of the second list, the second character of the first string in the first list to the second character of the first string in the second list, etc. I can think of two implementations.

The one I would start with:

var firstCharList = new List<char>();
var secondCharList = new List<char>();

firstList.foreach(s => 
 {
   foreach(char c in s)
   {
      firstCharList.Add(c);
   }
  });

secondList.foreach(s =>
{
   foreach(char c in s)
   {
      secondCharList.Add(c);
   }
});

for(int i = 0; i < firstCharList.Length; i++)
{
   if(firstCharList[i] == secondCharList[i]) yield return i;
}

That would generate a list (or array, or whatever) of ints that correspond to indexes of which both strings had the same character.

The second would be something like:

firstList.foreach(s =>
{
   var index = firstList.IndexOf(s);
   var sPrime = secondList[index];
   for(int i = 0; i < s.Length; i++)
   {
      if(s[i] == sPrime[i]) yield return s[i];
   }
}

That one just returns any characters that are equal at the same indexes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文