我正在尝试使用 Linq (C#) 创建一个列表,该列表是另一个列表的子集,其中要查询的值(来自文本框)介于列表对象的值之间:
这是我的代码
filteredMaps = allMaps
.Where(map =>
map.BeginningValue.CompareTo( textValueFilter.Text.Trim().ToUpper() ) <= 0
&&
map.EndingValue.CompareTo( textValueFilter.Text.Trim().ToUpper() ) >=0
)
.ToList();
执行此代码后,filteredMaps
始终为空。我想我在某处需要一个“选择”子句,但还没有弄清楚语法。
我是 Linq(和 lamdas)的新手
map 是 MapEntry 类型的对象,(部分)定义为
public readonly string BeginningValue;
public readonly string EndingValue;
allMaps 和 filteredMaps 都定义为
List<MapEntry>
我尝试了以下代码,结果相同:
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();
正如 stuartd 和 jmcilhinney 指出的那样,我的 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 总是大写的,所以我能够简化,但我会记下
你的问题不清楚。但是如果你想让
BeginningValue
和EndingValue
包含文本框字符串,使用下面的方法:
var filteredMaps = mapEntries.Where(map =>
map.BeginningValue.ToUpper().Contains(textValueFilter.Text.ToUpper())
&&
map.EndingValue.ToUpper().Contains(textValueFilter.Text.ToUpper())
).ToList();
如果想让
BeginningValue
和EndingValue
等于文本框字符串:
var filteredMaps = mapEntries
.Where(map =>
map.BeginningValue.Equals(textValueFilter.Text, StringComparison.CurrentCultureIgnoreCase)
&&
map.EndingValue.Equals(textValueFilter.Text, StringComparison.CurrentCultureIgnoreCase)
).ToList();