¿Cómo puedo obtener Linq en C# para devolver un SortedList
dado un IEnumerable
? Si no puedo, ¿es posible convertir o transformar el IEnumerable
en un SortedList
?C# Linq return SortedList
10
A
Respuesta
15
La manera más simple probablemente sería crear un diccionario usando ToDictionary
, y luego llamar al constructor SortedList<TKey, TValue>(dictionary)
. Alternativamente, añadir su propio método de extensión:
public static SortedList<TKey, TValue> ToSortedList<TSource, TKey, TValue>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
{
// Argument checks elided
SortedList<TKey, TValue> ret = new SortedList<TKey, TValue>();
foreach (var item in source)
{
// Will throw if the key already exists
ret.Add(keySelector(item), valueSelector(item));
}
return ret;
}
Esto le permitirá crear SortedList
s con los tipos anónimos como los valores:
var list = people.ToSortedList(p => p.Name,
p => new { p.Name, p.Age });
4
Usted tendrá que utilizar el constructor IDictionary
a fin de utilizar la extensión ToDictionary
método en su consulta linq y luego use el nuevo SortedList(dictionary);
por ej.
var list=new SortedList(query.ToDictionary(q=>q.KeyField,q=>q));
0
Algo como esto funciona bien
List<MyEntity> list = DataSource.GetList<MyEntity>(); // whatever data you need to get
SortedList<string, string> retList = new SortedList<string, string>();
list.ForEach (item => retList.Add (item.IdField, item.Description));
Cuestiones relacionadas
- 1. Cómo convertir una SortedList en una SortedList <>
- 2. C# más rápido de clasificación de SortedList <>
- 3. C++ virtual function return type
- 4. SortedList vs. SortedDictionary vs. Sort()
- 5. yield return versus return select
- 6. C++ plantilla determinar función return tipo
- 7. functor return 0
- 8. redirect_to! = Return
- 9. Función return type type
- 10. SWL swap on return?
- 11. ¿Hay alguna alternativa a Dictionary/SortedList que permita duplicados?
- 12. C# LINQ media
- 13. C# LINQ - Ejecución
- 14. C# Linq ¿Palabras clave?
- 15. "entre" en LINQ C#
- 16. LINQ seleccionar distinto C#
- 17. C# LINQ orden personalizado
- 18. C# Linq Grouping
- 19. FindName return null
- 20. En C#, ¿hay algún tipo de SortedList <double> que permita consultas rápidas (con LINQ) para el valor más cercano?
- 21. ¿Cuál es la diferencia entre "return View()" y "return PartialView()"
- 22. En el lenguaje C, ¿qué significa "return ~ 0"?
- 23. return from inside a @synchronized block in objective-c
- 24. C++: evitar la copia con la declaración "return"
- 25. Twisted MySQL adbapi return dictionary
- 26. Cruz se une Contexto - LINQ/C#
- 27. C# LINQ seleccionar de la lista
- 28. instrucción Return utilizando operador ternario
- 29. Moq caches return value
- 30. getLastVisiblePosition return -1