开发者

C# collections and grabbing property value of each into a new array

I have a list of 开发者_开发问答objects each with its own id property. I need to create an icollection of ids from the stored objects. Is there an elegant way other than looping through the list of objects, grabbing the id value and dumping it into the collection?


LINQ is your friend :)

List<int> ids = entities.Select(x => x.Id).ToList();

or into an array if you must (as per question title):

int[] ids = entities.Select(x => x.Id).ToArray();

Of course that does just iterate over the collections, but it's code you don't have to write yourself...

Basically, whenever you find yourself wanting to do "something like this" - transforming, aggregating, filtering, flattening etc a collection - you should look at whether LINQ can help you.


how about using Linq (which will do the iteration for you) using a Select() projection with the properties you want (in your case just the Id):

var idCollection = someList.Select(x=> x.Id).ToList();


Linq to the rescue:

var names=Controls.Select(w=>w.Name).ToArray();     // where this is a form
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜