比较 2 个字符串列表的第一个单词到一个控制字符

Compare 2 string List by the first word up to a control character

是否可以通过第一个单词到控制字符来比较 2 个字符串列表?

假设字符串是 -

"yellow/tall/wide/white"

有没有办法使用-

newList = listOne.Except( listTwo ).ToList();

但只比较第一个'/'

谢谢。

一个非常简单的方法如下:

var result = list1.Where(str1 => !list2.Any(str2 => str2.Split('/')[0] == str1.Split('/')[0]));

或者,您可以使用 Except,但这需要您创建自定义 IEqualityComparer:

public class CustomStringComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        // Ensure that neither string is null
        if (!object.ReferenceEquals(x, null) && !object.ReferenceEquals(y, null))
        {
            var x_split = x.Split('/');
            var y_split = y.Split('/');

            // Compare only first element of split strings
            return x_split[0] == y_split[0];
        }

        return false;
    }

    public int GetHashCode(string str)
    {
        // Ensure string is not null
        if (!object.ReferenceEquals(str, null))
        {
            // Return hash code of first element in split string
            return str.Split('/')[0].GetHashCode();
        }

        // Return 0 if null
        return 0;
    }
}

var result = list1.Except(list2, new CustomStringComparer());