简体   繁体   English

LINQ按错误分组:“不包含'GroupBy'的定义”

[英]LINQ Group by error: “does not contain a definition for 'GroupBy'”

I have a List that I need to group by. 我有一个列表需要分组。 In the list I add this object: 在列表中,我添加此对象:

private class MyObject {

        private System.Drawing.Color color;
        private string title;            

        public MyObject(System.Drawing.Color color, string title)
        {
            this.color = color;
            this.title = title;
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        public System.Drawing.Color Color
        {
            get { return color; }
            set { color = value; }
        }

}

I create my List as: 我将列表创建为:

System.Collections.Generic.List<MyObject> mList = new       System.Collections.Generic.List<MyObject >();

Then I try to group the content: 然后,我尝试对内容进行分组:

var groupedList = mList.GroupBy(c => new {c.Title} ).ToList();

And that is when I get the error. 那就是我得到错误的时间。 Any ideas? 有任何想法吗? How can I do this? 我怎样才能做到这一点? Thanks! 谢谢!

Those kinds of errors typically mean you aren't including System.Linq in your using list. 这些类型的错误通常意味着您不在使用列表中包括System.Linq Try throwing this at the top of your code file: 尝试将其扔到代码文件的顶部:

using System.Linq;

您是否有对System.Linq命名空间的引用?

You need to add using System.Linq to the file, at the top or inside of the namespace. 您需要using System.Linq将文件添加到名称空间顶部或内部。

GroupBy isn't actually a method of the List class, it's an extension method that is defined in System.Linq . GroupBy实际上不是List类的方法,它是System.Linq定义的扩展方法。 When you add a using statement to that namespace it allows all extension methods in that namespace to be resolve to any types they extend for the file the using is in. 当您将using语句添加到该命名空间时,它允许将该命名空间中的所有扩展方法解析为它们为using的文件扩展的任何类型。

Some unrelated notes: 一些不相​​关的注释:

  1. you probably also want to add a using System.Collections.Generic , as well as several other common namespaces to the top of that file, and likely most others. 您可能还想在该文件的顶部以及其他大多数顶部添加一个using System.Collections.Generic以及其他几个常见的命名空间。 Typing out System.Collections.Generic.List<MyObject> mList = new System.Collections.Generic.List<MyObject >(); 输入System.Collections.Generic.List<MyObject> mList = new System.Collections.Generic.List<MyObject >(); just makes me cringe. 只是让我畏缩。 Once you add that using you'll only need: List<MyObject> mList = new List<MyObjecT>(); 一旦添加using您将只需要: List<MyObject> mList = new List<MyObjecT>(); .
  2. You probably don't want to create a new anonymous class for your grouping. 您可能不想为分组创建新的匿名类。 It will work, but it'll make using the results that much more annoying without adding anything useful. 它将起作用,但是在不添加任何有用内容的情况下,使用结果会更加烦人。 Just do: mList.GroupBy(c => c.Title ) if you only want to group on the Title . 只需做: mList.GroupBy(c => c.Title )如果只想对Title进行分组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM