首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用Distinct()方法时,删除空字符串值并忽略C#列表中的大小写

在C#中,使用Distinct()方法可以从列表中删除重复的元素。然而,默认情况下,Distinct()方法不会删除空字符串值,并且会区分大小写。如果我们想要删除空字符串值并忽略大小写,可以自定义一个比较器。

首先,我们需要创建一个自定义的比较器类,实现IEqualityComparer接口。在这个比较器类中,我们可以定义比较两个元素是否相等的逻辑,并且可以忽略大小写。

下面是一个示例的自定义比较器类:

代码语言:txt
复制
public class IgnoreCaseStringComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        if (x == null && y == null)
            return true;
        if (x == null || y == null)
            return false;
        return string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(string obj)
    {
        if (obj == null)
            return 0;
        return obj.ToLower().GetHashCode();
    }
}

接下来,我们可以在使用Distinct()方法时,传入自定义的比较器对象来实现删除空字符串值并忽略大小写的功能。

代码语言:txt
复制
List<string> list = new List<string> { "apple", "banana", "", "Apple", "orange", "" };

List<string> distinctList = list.Distinct(new IgnoreCaseStringComparer()).Where(s => !string.IsNullOrEmpty(s)).ToList();

foreach (string item in distinctList)
{
    Console.WriteLine(item);
}

以上代码将输出:

代码语言:txt
复制
apple
banana
orange

在这个例子中,我们使用了自定义的比较器IgnoreCaseStringComparer来忽略大小写,并且使用Where()方法过滤掉空字符串值。最终得到的distinctList列表中包含了删除空字符串值并忽略大小写的结果。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云人工智能:https://cloud.tencent.com/product/ai
  • 腾讯云物联网通信(IoT Hub):https://cloud.tencent.com/product/iothub
  • 腾讯云移动推送(信鸽):https://cloud.tencent.com/product/tpns
  • 腾讯云区块链服务(BCS):https://cloud.tencent.com/product/bcs
  • 腾讯云元宇宙:https://cloud.tencent.com/product/tencent-meta-universe
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券