排序列表< T>使用查询表达式 [英] Sort a List<T> using query expressions

查看:121
本文介绍了排序列表< T>使用查询表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ订购这样的结构有一个问题:

I have a problem using Linq to order a structure like this :

public class Person
{
    public int ID { get; set; }
    public List<PersonAttribute> Attributes { get; set; }
}

public class PersonAttribute
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

一个人可能是这样的:

PersonAttribute Age = new PersonAttribute { ID = 8, Name = "Age", Value = "32" };
PersonAttribute FirstName = new PersonAttribute { ID = 9, Name = "FirstName", Value = "Rebecca" };
PersonAttribute LastName = new PersonAttribute { ID = 10, Name = "LastName", Value = "Johnson" };
PersonAttribute Gender = new PersonAttribute { ID = 11, Name = "Gender", Value = "Female" };



我想使用LINQ投影排序我的选择的人的属性提升的人员名单例如,排序上的年龄,或排序的名字。

I would like to use LINQ projection to sort a list of persons ascending by the person attribute of my choice, for example, sort on Age, or sort on FirstName.

我想是这样

string mySortAttribute = "Age"
PersonList.OrderBy(p => p.PersonAttribute.Find(s => s.Name == mySortAttribute).Value);



但语法失败我。任何线索?

But the syntax is failing me. Any clues?

推荐答案

排序依据是一个LINQ的扩展,产生一个新的序列。要订购您需要添加一个扩展方法或两个现有的序列......那么你可以使用:

OrderBy is a LINQ extension that produces a new sequence. To order the existing sequence you need to add an extension method or two... then you can use:

PersonList.Sort(p => p.Attributes.Find(
  s => s.Name == mySortAttribute).Value);

public static class ListExtensions {
  public static void Sort<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
  {
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(x), selector(y)));
  }
  public  static void SortDescending<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
  {
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(y), selector(x)));
  }
}

这篇关于排序列表&LT; T&GT;使用查询表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆