【发布时间】:2015-12-29 12:13:10
【问题描述】:
我有以下列表:
List<MyType> myList = new List<MyType>
{
new MyType {Key = "aa", Value = "test1"},
new MyType {Key = "bb", Value = "test2"},
new MyType {Key = "zz", Value = "testzz"},
new MyType {Key = "cc", Value = "test3"},
new MyType {Key = "yy", Value = "testyy"},
new MyType {Key = "dd", Value = "test4"},
new MyType {Key = "ee", Value = "test5"}
};
在哪里,
public class MyType
{
public string Key { get; set; }
public string Value { get; set; }
}
现在,我想根据 Key 的值检索范围内的所有对象。也就是说,我想从列表中选择从 Key="bb" 到 Key="dd" (无字母顺序)的所有对象,这样我就会得到以下结果:
new MyType {Key = "bb", Value = "test2"},
new MyType {Key = "zz", Value = "testzz"},
new MyType {Key = "cc", Value = "test3"},
new MyType {Key = "yy", Value = "testyy"},
new MyType {Key = "dd", Value = "test4"}
如何使用 linq/lambda 表达式实现这一点?
[更新:2015 年 12 月 30 日]:键未按字母顺序排列,可能有数百个键。因此,涉及 list.Contains(..) 并假设字母顺序的解决方案将不起作用。我还更新了示例以包含具有键 'yy' 和 'zz' 的对象以反映相同。
【问题讨论】:
-
您的标准实际上可以有多多样化?它们总是在一个范围内还是完全不相交?根据这一点,可能会有大不相同的答案。