0

I have 3 levels for a PlanSolution 1,2,3 and i need to sort by .levelId initially, and then alphabetically sort the solutions belonging to that level by .name

PlanSolution[] planSolutions = wsAccess.GetPlanSolutionsForPlanRisk(planRisk.Id);
                    List<PlanRisk> planSolutionsList = new List<PlanRisk>(planSolutions);


                    planSolutionsList.Sort(delegate(PlanSolution x, PlanSolution y)
                    {
                        //HELP lol
                    });
1
  • 1
    You don't need to create a List<T> just to do sorting. Just use the Array.Sort() method as well as one of the delegates provided in the many solutions. Linq may be overkill if your array is large, as it may require you to make a copy of it if you want to keep it as an array or list (via ToList() or ToArray()). Commented Aug 20, 2009 at 16:53

4 Answers 4

6

LINQ to the rescue!

planSolutionsList = planSolutions
    .OrderBy(x => x.id)
    .ThenBy(x => x.Name)
    .ToList(); // is this necessary?

For the original format -- you just want your comparer to prioritize ID over name

planSolutionsList.Sort( (x, y) => 
{
   //HELP lol
   if (x.id != y.id) return x.id - y.id;
   else return x.Name.CompareTo(y.Name);
});
Sign up to request clarification or add additional context in comments.

Comments

1

you could use Linq

planSolutionsList.OrderBy(x => x.Level).ThenBy(x => x.Name).ToList();

Comments

0

For a language-acnostic approach: Do each one in order.

1) Sort on the level. 2) Remember the starting locations of each level after sorting 3) repeat for next sorting crieteria, only sorting the sub-sections.

Comments

0
  planSolutionsList.Sort(delegate(PlanSolution x, PlanSolution y) {
    if (x.Level == x.Level) {            // same level, compare by name
      return x.Name.CompareTo(y.Name);
    } else {                             // different level, compare by level
      return x.Level.CompareTo(y.Level);
    }
  });

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.