简体   繁体   中英

How can i use GroupBy with a list of objects and return IList<T>?

i have a method that, must return a list of objects, but i don't know how! my problem is converting(or maybe casting)groupdResult to IList.

internal IList<MyClass> MyMethod()
        {
            IList<MyClass> result=new List<MyClass>();

            IList<MyClass> rawData = this.GetRawDatas();

            foreach (MyClass item in rawDatas)
            {
                // do somthings
                MyClass balancedData = new MyClass();  
                if(some conditions)
                {
                  result.Add(balancedData);
                }
            }
            var groupdResult = result.GroupBy(x => x.MyField).ToList();
            return groupdResult;
        }

Think about it: The result is either going to be a list of groups or a list of ungrouped objects. I believe that what you want is actually just a sorted list:

return result.OrderBy(x => x.MyField).ToList();

It's not the List/IList you're having trouble with. It's the fact that GroupBy does not return MyClass.

GroupBy returns an IGrouping, so the line

var groupdResult = result.GroupBy(x => x.MyField).ToList();

returns a List< IGrouping< MyClass > >.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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