LINQ按姓氏选择订单范围 [英] LINQ Select Range Of Orders By Surname

查看:84
本文介绍了LINQ按姓氏选择订单范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回想起来,我想这可能很明显,但是我发现很难绕开这个话题.

I guess this is probably going to be obvious in retrospect but I am finding it very hard to get my head round this.

我基本上只想使用LINQ to Objects从具有姓氏属性的对象范围中选择两个姓氏之间按字母顺序排列的姓氏,例如在列表中:

Basically I just want to use LINQ to Objects to select from a range of objects with a surname property the surnames alphabetically between two surnames e.g. in the list:


Adams
Bentham
Bickford
Gillies
Kelly
Moore
Peters
Rutherford
Smith
Taylor
Williams

如果您从凯利"选择为史密斯",它将返回:

If you selected from "Kelly" to "Smith" it would return:


Kelly
Moore
Peters
Rutherford
Smith

含.

必须足够具体,以至于要选择史密斯(Kelly)到史密斯(Kelly),并且在查询之前有一个凯勒曼(Kellerman)和之后有一个史密斯(Smythe),因此将那些排除在外,这样LIKE'K%'和LIKE'S%'不好.此外,您还必须仔细阅读k和s之间的所有字母才能到达那里.

It has to be specific enough that in the case where one were to select Kelly to Smith and there was a Kellerman before and a Smythe after the query would leave those out so LIKE 'K%' and LIKE 'S%' are no good. Besides you'd have to go through all the letters inbetween k and s to get there.

我向Google提出问题的方式很可能很愚蠢,但似乎没有其他人对此有顾虑.希望有人能帮忙.

I am likely just being foolish in the way I'm putting the question to Google but no one else seems to have this alphabetic concern. Hope someone can help.

到目前为止,很好的人.但是,这是一个聪明的人.我们要设置返回的最大记录数.

So far so good folks. But here's a brainrtwister. We want to set a Maximum number of records returned.

例如,如果我们要求比克福德到卢瑟福的最多3人,我们应该回去:

e.g If we ask for Bickford to Rutheerford with a max of 3 we should get back:


Bickford
Gillies
Kelly

目前,我们只是在球门柱之间随机获得三个名称.

At present we just get three of the names between the goalposts at random.

有什么想法吗?

推荐答案

我认为您正在寻找类似的东西

I think you're looking for something like this

static IEnumerable<string> GetNames(IEnumerable<string> originalList, string fromName, string toName)
{
    foreach (string name in originalList)
    {
        if (name.CompareTo(fromName) >= 0 && name.CompareTo(toName) <= 0)
            yield return name;
    }
}

或LINQ版本

static IEnumerable<string> GetNames(IEnumerable<string> originalList, string fromName, string toName)
{
    var query = from name in originalList
                where name.CompareTo(fromName) >= 0 && name.CompareTo(toName) <= 0
                select name;

    return query;
}

将您的凯利(Kelly)制作为史密斯(Smith)包含清单的示例用法

Example usage to product your Kelly to Smith inclusive list

string[] surnames = { "Adams", "Bentham", "Bickford", "Gillies", "Kelly", "Moore", "Peters", "Rutherford", "Smith", "Taylor", "Williams" };

foreach (string name in GetNames(surnames, "Kelly", "Smith"))
    Console.WriteLine(name);

这篇关于LINQ按姓氏选择订单范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆