【问题标题】:Compare 2 string List by the first word up to a control character比较 2 字符串列表的第一个单词到一个控制字符
【发布时间】:2017-09-18 19:45:07
【问题描述】:

是否可以通过第一个单词将 2 个字符串列表与控制字符进行比较?

假设字符串是 -

“黄/高/宽/白”

有没有使用-

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

但只比较第一个'/'

谢谢。

【问题讨论】:

  • 您可以在/ 上拆分并比较 0 索引吗?

标签: c# list except


【解决方案1】:

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

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());

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多