遇到一个问题,退出LINQ& LAMBDA

时间:2012-07-11 09:57:41

标签: linq lambda linqpad

根据我的要求,我设法从这个网站获得一个linq查询但是当我将所有内容粘贴到linq pad中时它会出错。在这里,我将粘贴完整的linq查询,我收到错误消息,如"名称' grp'在当前上下文中不存在"

void Main()
{
    List<SearchResult> list = new List<SearchResult>() {
    new SearchResult(){ID=4,Title="Wie man BBA reman erreicht"},
    new SearchResult(){ID=5,Title="Ersatz Airbags, Gurtstrammer und Auto Körper Teile "},
    new SearchResult(){ID=6,Title="JCB Excavator - ECU P/N: 728/35700"},
    new SearchResult(){ID=2,Title="Geo Prism 1995 GEO - ABS #16213899"},
    new SearchResult(){ID=3,Title="Geo Prism 1995 - ABS #16213899"},
    new SearchResult(){ID=1,Title="Geo Prism 1995 GEO GEO- ABS #16213899"},
    };

var to_search = new[] { "Geo", "JCB" };
var result = (from searchResult in list
             let title = searchResult.Title.ToLower()
             let key_string = to_search.FirstOrDefault(ts => title.Contains(ts))
             orderby key_string == null ? -1 : title.Split(new[] { key_string }, StringSplitOptions.None).Length descending
             group searchResult by key_string into Group
             select Group).OrderByDescending(grp => grp.Count()).ThenByDescending(CountStringOccurrences(**grp.Key**, to_search));
}

public int CountStringOccurrences(string text, string[] pattern)
{
// Loop through all instances of the string 'text'.
int count = 0;
foreach (string itm in pattern)
{ 
   int i = 0;
   while ((i = text.IndexOf(itm, i)) != -1)
   {
      i += itm.Length;
      count++;
    }
}
return count;
 }

public class SearchResult{
    public int ID { get; set; }
    public string Title { get; set; }
}

粗体区域正在抛出错误。谢谢plzz看看。

1 个答案:

答案 0 :(得分:2)

更改查询结尾
ThenByDescending(CountStringOccurrences(grp.Key, to_search));

ThenByDescending(grp => CountStringOccurrences(grp.Key, to_search));

因为Enumerable.ThenByDescending需要keySelector函数,并且您希望传递searchresult - Group。