0

I have a list of type Test

List<Test> testList = new List<Test> 
    { new Test { TestName="gold", CriteriaOne = "sport", CriteriaTwo = "Outdoors" },
    { new Test { TestName="silver", CriteriaOne = "sport", CriteriaTwo = "Indoors" }, 
    { new Test { TestName="bronze", CriteriaOne = "activity", CriteriaTwo = "Water" }, 
    { new Test { TestName="gold", CriteriaOne = "activity", CriteriaTwo = "Outdoors" }, 
                     //some more tests  ...      };

I have a list for each criteria

// List of strings to order testListBy first.
List<String> criteriaOneOrder = new List<String> { "sport", "activity", "warmup", "other"};

//List of strings to order testListBy second.
List<String> criteriaTwoOrder = new List<String> { "OutDoors", "Indoors", "Water", "Other"};

I want to order by list of type test firstly based on the criteriaOneOrder list then if two results are the same, ie. more than one sport then order them on the second string so that a outdoor sport will be listed before indoor sport.

I've tried using Lambda expressions making use of the OrderyBy function and the IndexOf to try and reorder the list but have not been successful so far.

testList = testList.OrderBy(t => criteriaOneOrder.IndexOf(t.CriteriaOne)).ToList()

Any ideas?

2 Answers 2

1

I would use enumarations to accomplish this:

enum CriteriaOne
{
    sport,
    activity,
    warmup,
    other
}

enum CriteriaTwo
{
    Outdoors,
    Indoors,
    Water,
    Other
}

var orderedList = testList
            .OrderBy(x => Enum.Parse(typeof (CriteriaOne), x.CriteriaOne))
            .ThenBy(x => Enum.Parse(typeof (CriteriaTwo), x.CriteriaTwo))
            .ToList();

If you change type of your properties to enum then you can simply do this:

var orderedList = testList
            .OrderBy(x => x.CriteriaOne)
            .ThenBy(x => x.CriteriaTwo)
            .ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

The parsing and casting is unnecessary. x => x.CriteriaOne is sufficient, and (IMO) perfectly clear.
0

Yep, its straightforward. Write a custom implementation of IComparer<string>, initialise it and pass it in as the second parameter for the LINQ OrderBy() method, and you are good to go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.