Jignesh Thakker
Jignesh Thakker

Reputation: 3698

way to go from list of objects to SortedList<string,string> with two of the fields using LINQ

I have class with 5 fields.

public class Test
{
public string name;
public string description;
public int int1;
public int int2;
public int int3;
}

In one of my function I have List<Test> list which has 10 items. Here I want SortedList<string,string> for two properties name & description.

I know, I can achieve this using for each but I want to know How can I do this using LINQ?

Upvotes: 0

Views: 405

Answers (3)

HugoRune
HugoRune

Reputation: 13809

A C# SortedList is a type of dictionary, not actually a list. If you indeed want a SortedList containing the names as keys and the descriptions as values, you can use this:

SortedList slist = new SortedList(list.ToDictionary(t=>t.name, t=>t.description))

Be aware that if a name occurs twice this will throw an exception, since dictionary keys have to be unique.

For most practical purposes however, the solution posted by Daniel Hilgarth is what I would use, unless you have a library function that specifically requires a SortedList as parameter.

Upvotes: 1

Wasp
Wasp

Reputation: 3425

The answer from @HugoRune is quite exhaustive, but because you said you want to use Linq, I'd suggest to add an extension method in your scope to help you with your goal:

static class SortedListExtensions
{
    public static SortedList<K, V> ToSortedList<K, V, T>(
        this IEnumerable<T> source, 
        Func<T, K> keySelector, Func<T, V> valueSelector)
    {
        return new SortedList<K,V>(
            source.ToDictionary(
                cur => keySelector(cur), 
                cur => valueSelector(cur)));
    }
}

this way your SortedList creation is composable in Linq computations:

var sl = list.ToSortedList(f => f.name, f => f.description);

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

Use this:

var result = list.OrderBy(x => x.Name).ThenBy(x => x.Description);

Important:

  1. Don't use multiple calls to OrderBy as they overwrite each other.
  2. The sorted result will be in result. The original list remains unchanged.

Upvotes: 4

Related Questions