You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C# Linq生成列表子集时结果为空的问题排查与解决

使用LINQ筛选包含指定文本的MapEntry子集

需求:从List<MapEntry>类型的allMaps列表中,筛选出BeginningValue和EndingValue包含文本框输入值的元素,生成子集列表filteredMaps。

初始尝试代码

方法链写法

filteredMaps = allMaps
    .Where(map =>
         map.BeginningValue.CompareTo( textValueFilter.Text.Trim().ToUpper() ) <= 0
         && 
         map.EndingValue.CompareTo( textValueFilter.Text.Trim().ToUpper() ) >=0
    )
    .ToList();

查询表达式写法

IEnumerable<MapEntry> mapEntries = (
    from map in allMaps
    where (
        map.BeginningValue.CompareTo( textValueFilter.Text.Trim().ToUpper() ) <= 0
        &&
        map.EndingValue.CompareTo( textValueFilter.Text.Trim().ToUpper()) >= 0 )
    select map
);

filteredMaps = mapEntries.ToList();

执行后filteredMaps始终为空,调整为查询表达式写法后结果依旧。

说明:MapEntry类型包含只读字符串字段BeginningValue和EndingValue,allMaps与filteredMaps均为List<MapEntry>类型。

问题原因与修正代码

问题出在CompareTo的使用逻辑上,原代码的比较逻辑无法实现“包含指定文本”的筛选需求。修正后的可行代码如下:

string filter = textValueFilter.Text.Trim().ToUpper();
            
IEnumerable<MapEntry> mapEntries = (from map in (IEnumerable<MapEntry>)allMaps
                        where(map.BeginningValue.Substring(0,filter.Length).CompareTo(filter) <= 0
                         && map.EndingValue.Substring(0,filter.Length).CompareTo(filter) >= 0) select map);
filteredMaps = mapEntries.ToList();

进一步简化

由于已知BeginningValue和EndingValue始终为大写,可以省略ToUpper()调用,进一步简化代码。

内容的提问来源于stack exchange,提问作者Mark Ainsworth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:45:01