根据属性值列出选择对象范围

时间:2015-12-29 12:13:10

标签: c# linq list lambda

我有以下列表:

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 =&#34; bb&#34;中选择列表中的所有对象。到Key =&#34; dd&#34; (没有字母顺序)所以我会得到以下结果:

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(..)并假设字母顺序的解决方案将无效。我还更新了示例,以包含带键的对象&#39; yy&#39;和&#39; zz&#39;反映一样。

4 个答案:

答案 0 :(得分:1)

如果您有一组不相交的键,那么您可以使用Contains运算符:

var keys = new [] { "bb", "cc", "dd" };

var result = myList.Where(x => keys.Contains(x.Key));

答案 1 :(得分:1)

我假设你在谈论两个特定项目之间的项目(在位置,而不是基于字母顺序)。

以下是如何做到这一点:

bool found_last = false;

var first = "bb";
var last = "dd";

var result = myList.SkipWhile(x => x.Key != first).TakeWhile(x =>
{
    if (x.Key == last)
    {
        found_last = true;
        return true;
    }

    return !found_last;

}).ToList();

答案 2 :(得分:0)

您只需使用Where

即可
string start = "bb";
string end   = "dd";

var rows = myList.Where(x => x.CompareTo(start) >= 0 && x.CompareTo(end) <= 0);

答案 3 :(得分:0)

试试这个: -

var kys = new[] { "bb", "cc", "dd" };
var Result = myList.Where(x => kys.Contains(x.Key));