-4
| ID         | Desc        | Priority     |
|:-----------|------------:|:------------:|
| 1          |        aabc |   Priority1     
| 2          |         xyz |   Priority3    
| 3          |         cba |   Priority5     
| 4          |          fg |   Priority2      
| 5          |         xdr |   Priority4    
| 6          |         pqr |   Priority1

Hi, I've above table stored in a form of an Array.

Array[] Values;


Values[0]={'ID','Desc','Priority'};
Values[1]={'1','aabc','Priority1'};
Values[2]={'2','xyz','Priority3'};
Values[3]={'3','cba','Priority5'};

Now I have to sort Values on the basis of priority so that my result comes as.

Values[0]={'ID','Desc','Priority'};
Values[1]={'1','aabc','Priority1'};
Values[2]={'4','fg','Priority2'};
Values[3]={'2','xyz','Priority3'};

help me write the code for this in C#

Ashish Kamat
  • 567
  • 4
  • 16
S7H
  • 1,421
  • 1
  • 22
  • 37
  • What is `Array` type. Any Definition ? – Rajeev Kumar Jan 14 '16 at 11:57
  • 1
    Possible duplicate of [Better way to sort array in descending order](http://stackoverflow.com/questions/5430016/better-way-to-sort-array-in-descending-order) – Rob Jan 14 '16 at 12:02
  • This is literally one line in LINQ. Have you tried anything? – Andrei Jan 14 '16 at 12:02
  • https://msdn.microsoft.com/en-us/library/bb383982.aspx , as @InBetween says it really not a good idea to have priority as string – maztt Jan 14 '16 at 12:13
  • Create a class for your table. dont use arrays like that. because there is no type safety or any information of how you represent your data. this makes your program hard to understand and can become real buggy. – M.kazem Akhgary Jan 14 '16 at 12:18

2 Answers2

1
using System.Linq;

Values.OrderBy(a => a[2]);

Without more context can't really say for sure but Values looks horrendous. Why not use, for instance, an int to define priorities?

InBetween
  • 32,319
  • 3
  • 50
  • 90
0

If you really have a DataTable then try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication66
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Desc", typeof(string));
            dt.Columns.Add("Priority", typeof(string));

            dt.Rows.Add(new object[] {1, "aabc", "Priority1"});     
            dt.Rows.Add(new object[] {2, "xyz", "Priority3"});     
            dt.Rows.Add(new object[] {3, "cba", "Priority5"});     
            dt.Rows.Add(new object[] {4, "fg", "Priority2"});     
            dt.Rows.Add(new object[] {5, "xdr", "Priority4"});     
            dt.Rows.Add(new object[] {6, "pqr", "Priority1"});

            DataTable results = dt.AsEnumerable()
                .OrderBy(x => x.Field<string>("Priority"))
                .CopyToDataTable();
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20