-2

I have list of object. I'm trying to sort it using one of the property.

I'm trying something like below:

items.OrderBy(x => x.Name).ToList()

items can contain values for Name like follows :

case 1 - abc,xyz,byc,myu
case 2 - abc3,xur2,iuy7

I want to sort list in descending order if any values contain int (numbers). So here in case 2, i want to sort in descending order. In case 1,sorting will be in ascending order. The question is how to identify whether list contains any integers or not? So that i can decide the ordering.

public class TestClass
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}
Manish Dhariwal
  • 61
  • 1
  • 1
  • 9
  • This isn't custom sorting, it's a *different* order direction based on the values. You can't change the order direction in the middle of the sorting operation so you'll have to decide what kind of ordering to use before you call `OrderBy()` or `OrderByDescending()` – Panagiotis Kanavos Jan 29 '19 at 09:52
  • 1
    You can extend your class with ``ICompare`` and make ``compare`` method with your own logic. Then when call your custom method and it order your list with your custom ``compare`` method. look at [this](https://support.microsoft.com/en-gb/help/320727/how-to-use-the-icomparable-and-icomparer-interfaces-in-visual-c) link for more informations. you can find example and more – Paul Jan 29 '19 at 09:54

1 Answers1

2

You could use Any and char.IsDigit to determine if there is one:

if(items.Any(x => x.Name.Any(char.IsDigit)))
{
    // descending  
    items = items.OrderByDescending(x => x.Name)).ToList()
}
else
{
    // ascending
    items = items.OrderBy(x => x.Name)).ToList()
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    this condition `char.IsDigit` will also met at none latin digits like thai digits https://stackoverflow.com/questions/228532/difference-between-char-isdigit-and-char-isnumber-in-c-sharp – fubo Jan 29 '19 at 09:53
  • @Rango : Thank you. This is exactly what i was looking for. – Manish Dhariwal Jan 29 '19 at 10:18