如何根据字符串值通过LINQ查询List的内容?

时间:2013-11-12 19:22:19

标签: c# string linq generics ienumerable

我正在尝试使用“> =”查询字符串列/成员的记录集合。

我希望/期待的是,如果“音乐家”成员中有以下值,则会出现这样的情况:

Clarence "Gatemouth" Brown
Merle Travis
Eddie Van Halen
Rory Gallagher
Elvin Bishop
Eric Clapton
Jimi Hendrix
Stevie Ray Vaughan
Robin Trower
Ritchie Blackmore
Carlos Santana
Mark Knopfler
Pete Anderson

...以及以下LINQ查询:

private readonly List<Musician> musicians = new List<Musician>();
. . .
public IEnumerable<Musician> Get(string musician)
{
    IEnumerable<Musician> Musicians = from m in musicians
                                      where m.musician >= musician
                                      select m;
    . . .

...以“Robin”作为“音乐家”arg传递,返回IEnumerbale音乐家集合,其中包含音乐家值为的记录:

Robin Trower
Rory Gallagher
Stevie Ray Vaughan

(IOW,任何“大于”Robin的内容,例如在SQL查询中使用“ORDER BY MUSICIAN”子句时从“Robin”开始会出现的内容)。

而不是按预期工作,它甚至不编译,我得到,“运算符'&gt; ='不能应用于'string'和'string'”类型的操作数“ .musician&gt; =音乐家“LINQ查询的一部分。

那么如何使用LINQ过滤字符串值的“记录”集合呢?

6 个答案:

答案 0 :(得分:1)

你应该使用String.Compare(str1,str2)返回:

  • 如果str1小于str2
  • ,则小于零
  • 如果str1大于str2
  • ,则大于零
  • 0 str1等于str2

Here is the link to the documentation

    var musicians = new List<string>()
    {
        "Clarence \"Gatemouth\" Brown",
        "Merle Travis",
        "Eddie Van Halen",
        "Rory Gallagher",
        "Elvin Bishop",
        "Eric Clapton",
        "Jimi Hendrix",
        "Stevie Ray Vaughan",
        "Robin Trower",
        "Ritchie Blackmore",
        "Carlos Santana",
        "Mark Knopfler",
        "Pete Anderson",
    };

    var musician = "Robin";
    var newMusicians = musicians.Where(m => 0 < String.Compare(m,  musician));

    MessageBox.Show(String.Join(Environment.NewLine, newMusicians.ToArray()));

或者如果您更喜欢类似sql的语法:

var newMusicians = from m in musicians
                where 0 < String.Compare(m, musician)
                select m;

答案 1 :(得分:1)

我认为您可能正在寻找以下内容,它会在搜索字符串中的任何位置找到给定的子字符串。但是,它不会搜索搜索条件字符串的每个可能的子字符串。

IEnumerable<Musician> Musicians = musicians.Where(m => m.IndexOf(musician, StringComparison.CurrentCultureIgnoreCase) >= 0);

答案 2 :(得分:1)

var newList = myList.OrderBy(m => m).Where(m => string.Compare(m, "Robin") > 0);

其中myList是您的字符串值列表。

答案 3 :(得分:1)

您可以在LINQ查询中使用String.Compare,如下所示:

IEnumerable<Musician> Musicians = from m in musicians
                                          where String.Compare(m.musician, musician) > 0
                                          select m;

答案 4 :(得分:1)

var Musicians = MusicianList
          .Where(m => string.Compare(m.musician, musician) >= 0)
          .OrderBy(m=>m.musician);

返回您想要的结果

答案 5 :(得分:1)

用以下内容替换您的查询:

IEnumerable<Musician> Musicians = from m in musicians
                                  where string.Compare(m.musician, musician, true) > 0
                                  select m;