2

How can i achieve Sorting of a List<Dictionary<string, string>>.

I would like to sort the list on the basis of first element in the Dictionary.

My data Looks like

{
{{PID,A123},{SKU,TA50},{QTY,50}},
{{PID,C123},{SKU,TA52},{QTY,50}},
{{PID,B123},{SKU,TA53},{QTY,50}},
{{PID,A222},{SKU,TA54},{QTY,50}}
}

I am trying to get the output to look like

{
{{PID,A123},{SKU,TA50},{QTY,50}},
{{PID,A222},{SKU,TA54},{QTY,50}},
{{PID,B123},{SKU,TA53},{QTY,50}},
{{PID,C123},{SKU,TA52},{QTY,50}}
}

Solutions tried list.Sort - Not working since the contents are dictionary. list.OrderBy - Method not available.

Technology Working on - Visual Studio Community 2017, .NET 4.6.1, Console Application

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Angad Arora
  • 719
  • 10
  • 25

2 Answers2

3

How about Linq OrderBy() combined with key access of the Dictionary ["PID"]

items = items.OrderBy(x => x["PID"]).ToList();

so the Dictionaies are ordered, but themselves have no order

fubo
  • 44,811
  • 17
  • 103
  • 137
3

If you want to sort list by dictionary key then

var result = list.OrderBy(dict => dict["PID"]).ToList();

You need to refrenced using System.Linq; in your program to avail OrderBy in intellisense.

er-sho
  • 9,581
  • 2
  • 13
  • 26
  • Thank you for your time, as per the community if two answers are correct and same solution, i had to select the answer which came first. But thank you so much for your support. – Angad Arora Dec 06 '18 at 12:19
  • 1
    @AngadArora, Glad to hear...No problem.. fubo's and my answer posted on difference of few seconds only...welcome :) – er-sho Dec 06 '18 at 12:27