开发者

Combining Variable Numbers of Lists w/ LINQ

I have a list (List) of objects. Each of those objects contains a list (List) of strings describing them.

I'm needing to create a dropdown containing all of the distinct strings used to describe the objects (Cards). To do this, I need a list of distinct strings used.

Any idea how/i开发者_开发技巧f this can be done with LINQ?


You can use the SelectMany extension method/operator to flatten a collection into the individual elements.

listOfObjects.SelectMany(x => x.DescriptionStrings).Distinct()

This will select all the strings out of the collection of description strings for each object in your list of objects.


LINQ has a Distinct function.

Assuming "_cards" exists as instance variable of List and Card.Descriptions returns the descriptions and "cardsComboBox" (in WinForms):

cardsComboBox.AutoCompleteSource = _cards.SelectMany(c => c.Descriptions).Distinct();

A reminder that that will be the list of card descriptions at the time of binding however. If you want to keep it synchronised when _cards get updated then you'll have to do some more fancy footwork or look at a reactive binding source. (We use Bindable.Linq)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜