ravella
ravella

Reputation: 116

Filtering out values from a list of object in a List

I have an IEnumerable collection of UnitGroup: IEnumerable<UnitGroup>,

class UnitGroup
    {      
        string key { get; set; }              
        List<UnitType> NameList { get; set; }
    }
class UnitType
    {               
        String UnitName{ get; set; }
        Description { get; set; }
    }

Now I want to filterIEnumerable<UnitGroup> based on UnitType's UnitName.

For example I want to get only the records of UnitName that contains a string and remove remaining.

something like this:

IEnumerable<UnitGroup> Groups;
IEnumerable<UnitGroup> filteredResult = Groups.NameList(o => o.UnitName.contains("test"));

And get IEnumerable<UnitGroup> with only filtered UnitNames under UnitType under UnitGroup.

What is the best way of acheiving this?

Upvotes: 0

Views: 50

Answers (3)

Brent Stewart
Brent Stewart

Reputation: 1840

Here is another way that should do what @MarcinJuraszek answers does. (I am guessing the intent of the question as well.)

IEnumerable<UnitGroup> Groups;
var filteredResult = Groups.Where (g => g.NameList.Count() > g.NameList.RemoveAll(nl => nl.UnitName != "Name1"));

If the number of removed items was less than the original count, then we have items that are of interest, so select the parent.

Note: This will modify the original collection, so if you need to filter it more than once then this is not the answer you are looking for.

Upvotes: 1

Pieter Geerkens
Pieter Geerkens

Reputation: 11893

Try this:

  var filteredList = from g in Groups 
                     where g.NameList.Exists(i=>i.UnitName=="test")
                     select g;

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

I'm not 100% sure what you're trying to achieve. Could you provide some sample data, to make it more clear?

Although, I think it may fit into your goal:

IEnumerable<UnitGroup> Groups;
var filteredResult = Groups.Select(g => new UnitGroup {
                                            key = g.key,
                                            NameList = g.NameList
                                                        .Where(n => n.UnitName == "test")
                                                        .ToList()
                                        })
                           .Where(g => g.NameList.Count > 0);

Upvotes: 2

Related Questions