Reputation: 3698
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
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
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
Reputation: 174329
Use this:
var result = list.OrderBy(x => x.Name).ThenBy(x => x.Description);
Important:
OrderBy
as they overwrite each other.result
. The original list
remains unchanged.Upvotes: 4