tags:

views:

116

answers:

4

What I have is basically:

public class Object{
    public bool IsObjectValid { set; get; }
}

public class MyThing{
    public List<Object> Objects { set; get; }
}

What I want to do:

public class ObjectsFiltered{
    public List<Object> ValidObjects{
        get{
            var list = LFs.Sort<_LF> where (IsObjectValid == true);
            return list;
        }
    }
}

I know there has to be a way to sort out the List, filtering out the bool true/false. I just can't seem to wrap my head around Linq fully. I just can't seem to find a tutorial that screams "AH HA!" about Linq Lambda to me :/

I'd rather just return a subset, only only keep one "object" alive... instead of my current setup of multiple sets of lists. KISS.

Ultimately I will use the bool-toggles to feed TreeViews on my WPF form(s).

Clarification: I think the goal is to have a one list (List Objects) and a couple properties that show a filtered version of Objects. Instead of having Objects, ObjecstValid, ObjectsInvalid, ObjectsSomeOtherRuleSet... each a different List...

I'd like to have One List to rule them all... and have properties that return a variation on the list, as desired.

+4  A: 

You can use LINQ:

public IEnumerable<Object> ValidObjects{ 
    get{ 
        return LFs.Where(item => item.IsObjectValid)
                  .OrderBy(item => item.SomeProperty); 
    } 
} 

Unless you need a List<T>, it's better to return an IEnumerable<T>, so that you won't store it all in-memory.

The lambda expression item => item.SomeProperty is an inline function that takes a parameter called item and returns item.SomeProperty. (The parameter and return types are inferred by the compiler)

SLaks
I think this is what I'm looking for. I've seen similar setups on other questions here, just so hard putting pieces together. Once I figure out why XAML is now yelling at me, I'll report back.
WernerCD
A: 

To filter your objects, you can return simply:

return LFs.Where(x => x.IsObjectValid).ToList();

Note, however, that if you intend to draw on that function frequently, you may see some performance boost by maintaining a pre-filtered list internally.

kbrimington
+1  A: 

I found these samples very helpful when I first started learning LINQ.

Christopherous 5000
A: 
 LFs.Where(x => x.IsObjectValid).ToList().Sort()

To sort useing default compared. Otherwise

 LFs.Where(x => x.IsObjectValid).OrderBy(x => x.PropertyToSortBy).ToList(); 
Tomislav Markovski
`Sort()` returns `void`.
SLaks