【发布时间】:2017-09-18 19:45:07
【问题描述】:
是否可以通过第一个单词将 2 个字符串列表与控制字符进行比较?
假设字符串是 -
“黄/高/宽/白”
有没有使用-
newList = listOne.Except( listTwo ).ToList();
但只比较第一个'/'
谢谢。
【问题讨论】:
-
您可以在
/上拆分并比较 0 索引吗?
是否可以通过第一个单词将 2 个字符串列表与控制字符进行比较?
假设字符串是 -
“黄/高/宽/白”
有没有使用-
newList = listOne.Except( listTwo ).ToList();
但只比较第一个'/'
谢谢。
【问题讨论】:
/ 上拆分并比较 0 索引吗?
一个非常简单的方法如下:
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());
【讨论】: