Get a list greater than specific value from lists usinq linq c#

As juharr said, use proper classes with properties. But the short and dirty answer would be lists.Where(l => (double)l[1] > 1);, but it assumes that you always have at least two objects in your inner lists and that the second one is always a double. Which is why you should use a strongly-typed object with strongly-typed properties instead.

The correct way to handle it would be something like:

public class MyStuff
{
    public List<MyThing> Things { get; set; }
}

public class MyThing
{
    public string Name {get; set;}
    public double SomeValue {get; set;}
    public int SomeInt {get; set;}
}

var stuff = new MyStuff()
{
    Things = new List<MyThing>()
    {
        new MyThing() { Name = "dfg", SomeValue = 0.3, SomeInt = 7 },
        new MyThing() { Name = "fhc", SomeValue = 1.7, SomeInt = 8}
    }
};

var filtered = stuff.Things.Where(t => t.SomeValue > 1);

But preferably with meaningful class and property names!

In this case, Things can only include instances of MyThing and nothing else. And MyThing will always have a SomeValue (which will default to zero, unless you do something else with it) so the >1 test will never throw an exception

Browse More Popular Posts

Leave a Comment