C# Linq OrderBy(x => x.property)[英] C# Linq OrderBy(x => x.property)

本文是小编为大家收集整理的关于C# Linq OrderBy(x => x.property)的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

public class data() {
   public string attribute1 { get; set; }
   public string attribute2 { get; set; }
   public string attribute3 { get; set; }
}

我有一个对给定属性排序的列表.

_list.OrderBy(x => x.attribute1).ToList();

但是我想先定义对象,然后按照给定对象的顺序执行顺序.我想知道这是否可能.例如:

object myAttribute = attribute1;
_list.OrderBy(x => x.myAttribute).ToList();

推荐答案

如果需要创建动态 order by 语句,可以这样:

Func<Item, Object> orderBy = null;

if(...)
   orderBy = item => item.attribute1 ;
else 
  orderBy = item => item.attribute2;

_list.OrderBy(orderBy).ToList();

本文地址:https://www.itbaoku.cn/post/1557182.html

问题描述

public class data() {
   public string attribute1 { get; set; }
   public string attribute2 { get; set; }
   public string attribute3 { get; set; }
}

I have a list that orders the given attribute.

_list.OrderBy(x => x.attribute1).ToList();

But I want to define the object first and then execute order in order with the give object. I am wondering if this is possible. for example:

object myAttribute = attribute1;
_list.OrderBy(x => x.myAttribute).ToList();

推荐答案

If you need to create dynamic order by statements, you can do it like this:

Func<Item, Object> orderBy = null;

if(...)
   orderBy = item => item.attribute1 ;
else 
  orderBy = item => item.attribute2;

_list.OrderBy(orderBy).ToList();