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

本文关键字:选择 对象 范围 | 更新日期: 2023-09-27 18:28:19

我有以下列表:

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表达式实现这一点?

[更新:12/30/2015]:密钥不是按字母顺序排列的,可能有数百个密钥。所以,解决方案涉及列表。包含(..)并假定字母排序将不起作用。我还更新了这个例子,将键为"yy"answers"zz"的对象包括在内,以反映相同的情况。

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

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

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

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

以下是您的操作方法:

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();

试试这个:-

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

您可以简单地使用Where:

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