C# List<T> get return a sorted list
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.
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)
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.
LFs.Where(x => x.IsObjectValid).ToList().Sort()
To sort useing default compared. Otherwise
LFs.Where(x => x.IsObjectValid).OrderBy(x => x.PropertyToSortBy).ToList();
精彩评论