Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a TryParse inside Linq Comparable?

Tags:

c#

linq

A sort of:

Documenti = Documenti
    .OrderBy(o => string.IsNullOrEmpty(o.Note))
    .ThenBy(o => Int32.TryParse(o.Note))
    .ToList();

That will "ignore" (not order, putting at the end) if o.Note is "" or not an int.

How can I do it?

like image 284
markzzz Avatar asked May 17 '13 15:05

markzzz


People also ask

What is TryParse used for?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.

What is the use of TryParse command in C#?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.


1 Answers

Everyone who uses C#7 or newer scroll to the bottom, everyone else can read the original answer:


Yes, you can, if you pass the correct parameters to int.TryParse. Both overloads take the int as out-parameter and initialize it inside with the parsed value. So like this:

int note;
Documenti = Documenti
    .OrderBy(o => string.IsNullOrEmpty(o.Note))
    .ThenBy(o => Int32.TryParse(o.Note, out note)) 
    .ToList();

The clean approach is using a method that parses to int and returns int? if unparseable:

public static int? TryGetInt(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}

Now you can use this query(OrderByDescending because true is "greater" than false):

Documenti = Documenti.OrderByDescending(d => d.Note.TryGetInt().HasValue).ToList();

It's cleaner than using a local variable that is used in int.TryParse as out parameter.

Eric Lippert commented another answer of me where he gives an example when it might hurt:

C# LINQ: How is string("[1, 2, 3]") parsed as an array?


Update, this has changed with C#7. Now you can declare the variable directly where you use out parameters:

Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note, out int note)) 
.ToList();
like image 173
Tim Schmelter Avatar answered Oct 06 '22 21:10

Tim Schmelter