Conor
Conor

Reputation: 781

C# - Getting the 3 lowest values in a List, measured by a public property of the objects within the List

Sorry if my terminology is not great, I'm not a professional programmer.

I have a List< Something >, whereby the 'Something' is a struct. This struct contains objects, which each have their own public properties/fields in the classes. I want to sort the list in order - but by the values found in these nested properties/fields. Then I want to return a list of these values, not the structs.

I know this is very confusing but I've had trouble trying to do it. At the moment I just get a list returned with a count of 20 (which is the full data set I'm using), but I want the 3 values only with the smallest value.

For context and further explanation, here is some code I'm using:

        // Returns 3 nearest stations to the location specified
    public static List<TrainStation> nearbyStations(GeoCoordinate location)
    {
        List<StationWalk> stations = new List<StationWalk>();
        foreach (TrainStation s in All)
        {
            stations.Add(new StationWalk(s, new Walk(location, s.location)));
        }

        // return 3 TrainStation objects that have the lowest StationWalk.Walk.duration values corresponding with them in the StationWalk struct
        stations.OrderBy(walks => walks.walk.duration).Take(3);

        List<TrainStation> returnList = new List<TrainStation>();
        foreach (StationWalk s in stations)
        {
            returnList.Add(s.station);
        }
        return returnList;
    }

    private struct StationWalk
    {
        public StationWalk(TrainStation station, Walk walk)
        {
            this.station = station;
            this.walk = walk;
        }

        public TrainStation station;
        public Walk walk;
    }

'Walk' is a class that contains a 'duration' field. This represents the time it takes to walk. More specifically, my overall goal here is to figure out which 3 walks are the fastest walks out of all 20 in the list. But the 'walks' are properties of the StationWalk struct, and the 'duration' is a property of the Walk.

How would I go about doing this? Really sorry if this isn't well explained, it's confusing to myself despite writing it myself, yet alone trying to explain it to others.Appreciate any help.

Upvotes: 0

Views: 85

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

The OrderBy and Take both return a new collection, they do not modify the existing collection, so you would need to store the reference to new collection returned by the methods like:

stations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();

and if you want to keep reference to the original list for further usage down in your code, then just store the result in a local variable:

var lowestThreeStations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();

Upvotes: 4

Related Questions