Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<T> get return a sorted list

Tags:

c#

list

linq

c#-4.0

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.

like image 787
WernerCD Avatar asked Oct 12 '25 12:10

WernerCD


1 Answers

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)

like image 65
SLaks Avatar answered Oct 14 '25 00:10

SLaks