0

I have the following code but am having issues with how to maintain the order:

var cars = (from DataRow dRow in dt.AsEnumerable()
                            select new
                            {
                                Car = dRow["Car"],
                                CarId = dRow["CarId"],
                                CarOrder = dRow["CarOrder"]
                            }).Distinct();

The distinct works well but I need to preserver the CarOrder which goes from 1 to X (ascedning).

The DataTable dt have them all in order correctly but when it hits this distinct code the order does not get preserved.

I am trying to figure out how to use the OrderBy clause.

cdub
  • 24,555
  • 57
  • 174
  • 303
  • I don't get the question. You're having problems using `OrderBy()` (or the query syntax `order by`)? What's wrong? Your existing code doesn't guarantee any ordering. – gunr2171 Apr 16 '21 at 20:40
  • How do I use OrderBy on CarOrder with Distinct? I am unsure how to use it. – cdub Apr 16 '21 at 20:44
  • 1
    You add `.OrderBy` after your Distinct call. Do you know how OrderBy works? – gunr2171 Apr 16 '21 at 20:45
  • I need this to work }).Distinct().OrderBy("CarOrder"); – cdub Apr 16 '21 at 20:48
  • 1
    I think you need to go back and learn how LINQ works. You can't pass a string argument to OrderBy. Please do some reading [on how it works](https://www.tutorialsteacher.com/linq/linq-sorting-operators-orderby-orderbydescending). You've got _double_ the reputation I've got, so this is something I'd expect from you to have done already. – gunr2171 Apr 16 '21 at 20:51
  • 1
    Does this answer your question? [LINQ : Distinct and Orderby](https://stackoverflow.com/questions/14636142/linq-distinct-and-orderby) – devlin carnate Apr 16 '21 at 20:53

1 Answers1

0

According to docs

It returns an unordered sequence of the unique items in source

That means that order does not get preserved. So what you can do is probably OrderBy() after the Distinct() as following:

var cars = (from DataRow dRow in dt.AsEnumerable()
            select new
            {
                Car = dRow["Car"],
                CarId = dRow["CarId"],
                CarOrder = dRow["CarOrder"]
            }).Distinct().OrderBy(x => x.CarOrder);

See: Does Distinct() method keep original ordering of sequence intact?

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28