.net(C#)比较两个字符串列表并删除不匹配的元素
有什么方法可以比较两个字符串列表(不区分大小写),或者我需要为这种比较编写自定义代码吗?我还想从字典中删除不匹配的项 e、 g.net(C#)比较两个字符串列表并删除不匹配的元素,c#,C#,有什么方法可以比较两个字符串列表(不区分大小写),或者我需要为这种比较编写自定义代码吗?我还想从字典中删除不匹配的项 e、 g List lst1=新列表(); lst1.添加(“价值1”); lst1.添加(“价值2”); List lst2=新列表(); lst2.添加(“价值1”); lst2.添加(“价值2”); lst2.添加(“价值3”); 现在,在比较之后,我只希望在lst2中有“value1”和“value2” 问候,, JS您可以使用枚举.Intersect方法 有关示例,请
List lst1=新列表();
lst1.添加(“价值1”);
lst1.添加(“价值2”);
List lst2=新列表();
lst2.添加(“价值1”);
lst2.添加(“价值2”);
lst2.添加(“价值3”);
现在,在比较之后,我只希望在lst2
中有“value1”和“value2”
问候,,
JS您可以使用
枚举.Intersect
方法
有关示例,请参阅MSDN文档:
关于实现不区分大小写的比较,请参考Dyppl的答案。您可以使用
Intersect
扩展方法。要在INSTIVE中执行此操作,可以使用equaty比较器:
class Program
{
static void Main(string[] args)
{
List<string> lst1 = new List<string>();
List<string> lst2 = new List<string>();
CaseInsensitiveEquityComparer comparer = new CaseInsensitiveEquityComparer();
var result = lst1.Intersect(lst2, comparer);
}
}
class CaseInsensitiveEquityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return String.Compare(x,y,true,CultureInfo.CurrentCulture) == 0;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
类程序
{
静态void Main(字符串[]参数)
{
List lst1=新列表();
List lst2=新列表();
CaseInsensitiveEquityComparer comparer=新的CaseInsensitiveEquityComparer();
var result=lst1.Intersect(lst2,比较器);
}
}
类案例不敏感公平比较者:公平比较者
{
公共布尔等于(字符串x、字符串y)
{
返回String.Compare(x,y,true,CultureInfo.CurrentCulture)==0;
}
public int GetHashCode(字符串obj)
{
返回obj.GetHashCode();
}
}
您可以使用LINQ方法
您可以通过使用来避免创建自己的IEqualityComparer
实现
如果希望结果在lst2
中,请按如下方式执行:
lst2 = lst1.Intersect(lst2, StringComparer.InvariantCultureIgnoreCase).ToList();
请修复您的示例,它应该是lst1和lst2Nah,请参阅我的答案,您可以使用
StringComparer
谢谢Dyppl!更新了答案。这真是太酷了。通过ToUpper
-对字符串进行比较?在C#中不好,只需使用字符串。将与相应的options@Dyppl是的,但是很匆忙。现在修好了;)
var result = lst1.Intersect(lst2, StringComparer.InvariantCultureIgnoreCase);
lst2 = lst1.Intersect(lst2, StringComparer.InvariantCultureIgnoreCase).ToList();