# Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property

Once stuck on a requirement where I needed to write a code which is flexible and generic enough to sort any type of collection and also the property based on which it has to be sorted will be dynamic. After trying many options I discovered myself how easy it is to hit this requirement using Lamda Expression.

Below code will do this for you.

```public class Utility
{
///
/// Gets the sorted list.
///

///The source.
///The sort column.
///The sort direction.
/// private List GetSortedList(List source, string sortColumn, SortDirection sortDirection)
{
// Prepare the dynamic sort expression
var paramExp = Expression.Parameter(typeof(T), typeof(T).ToString());
Expression propConvExp =
Expression.Convert(Expression.Property(paramExp, sortColumn), typeof(object));
var sortExp = Expression.Lambda&gt;(propConvExp, paramExp);

if (sortDirection == SortDirection.Ascending)
{
return source.AsQueryable().OrderBy(sortExp).ToList();
}
else
{
return source.AsQueryable().OrderByDescending(sortExp).ToList();
}
}
}
```

We will call this method as below

```List sortedEmployees
= new Utility().GetSortedList(employeeList, "City", SortDirection.Ascending);
```

First we create the parameter expression for the generic type and on the further two statements we are promting the expression to convert the dynamic property based on which we need to sort to a understandable format of lambda. Then we go ahead and use the sort of generic list.

You can find the complete post over here as well

DON'T MISS OUT!
{"ft_lang_label":"__label__en","ft_lang_prob":0.7333252,"math_prob":0.8111351,"size":1465,"snap":"2022-40-2023-06","text_gpt3_token_len":300,"char_repetition_ratio":0.13073237,"word_repetition_ratio":0.0,"special_character_ratio":0.21569966,"punctuation_ratio":0.14919356,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95369226,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-02T18:53:27Z\",\"WARC-Record-ID\":\"<urn:uuid:82e3a00b-9c92-4af4-99cf-3d85bd80eac7>\",\"Content-Length\":\"275496\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:82648571-029e-4a48-bdc0-3c3fcf6bf584>\",\"WARC-Concurrent-To\":\"<urn:uuid:a9418675-a0f1-42df-97ad-dcc87a53f24f>\",\"WARC-IP-Address\":\"198.71.233.96\",\"WARC-Target-URI\":\"https://dailydotnettips.com/sort-generic-list-using-lambda-expression-for-dynamic-type-and-dynamic-property/\",\"WARC-Payload-Digest\":\"sha1:3OBMYPXK4KLGPWPMWDU3XYZ2BKM7VNKT\",\"WARC-Block-Digest\":\"sha1:YZ2UNOPG5MDWI4UDCAYF4EUT5G5ZKQEZ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500035.14_warc_CC-MAIN-20230202165041-20230202195041-00078.warc.gz\"}"}