简体   繁体   中英

C# LINQ Grouping Question

I have an object which is structured as below

public MyObject{
    int SomeNumber {get;set;}
    Object SomeObject {get;set;}
    Object SomeOtherObject {get;set;}
}

Now SomeNumber is not unique, If I have an IEnumerable How can I pull out an IEnumerable<MyObject> that all have the same SomeNumber Value?

I assume I need to use GroupBy to do this? But cant seem to get it right.

Edit: I dont know what SomeNumber is.

No need for GroupBy unless you want to make groups of them.

IEnumerable<MyObject> myEnumerable ...
myEnumerable.Where(o => o.SomeNumber == value);
IEnumerable<MyObject> source = something;
var grouped = source.GroupBy(s => s.SomeNumber);
var myObjects = new List<MyObject>(); // fill        

var groups = from item in myObjects group item by item.SomeNumber;
// alternatively:
// var groups = myObjects.GroupBy(item => item.SomeNumber)

foreach (var g in groups)
{
    var someNumber = g.Key;
    var members = g.ToList();
}

should do.

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