[英]C# Linq in extension / method
Greetings 问候
I'm looking for creating a extension method including a linq query. 我正在寻找创建包含linq查询的扩展方法。 What i'm looking for is either a method or extension method which can do something like this
我正在寻找的是可以做这样的事情的方法或扩展方法
var orderedList = OrderThisList<ModelName>(List<T> sourceList, //and something like m=>m.Username);
Where ModelName is the entity and Username is the field of which I want to order. 其中ModelName是实体,而Username是我要订购的字段。 The method would look something like
该方法看起来像
public List<T> OrderThisList<T>(//some linq property?)
{
//What code goes here?
}
EDIT: It's still extremely unclear what this question is all about, but it sounds like we're dealing with in-memory collections rather than LINQ to SQL etc. 编辑:仍然非常不清楚这个问题是什么,但听起来我们正在处理内存中的集合,而不是LINQ to SQL等。
If the problem with using OrderBy
is that it doesn't sort the list in-place, you should be using List<T>.Sort()
, possibly passing in a custom comparator. 如果使用
OrderBy
的问题在于它不能就地对列表进行排序,则应该使用List<T>.Sort()
,可能会传入自定义比较器。
My MiscUtil project has a few helper types which may help you. 我的MiscUtil项目有一些帮助程序类型,可能会对您有所帮助。 For example:
例如:
var comparison = ProjectionComparer<ModelType>.Create(m => m.SomeProperty)
.ThenBy(m => m.SomeOtherProperty);
list.Sort(comparison);
If you're using LINQ to SQL and you've got a data context , you could use: 如果您使用的是LINQ to SQL,并且具有数据上下文 ,则可以使用:
public List<TSource, TKey> OrderThisList<TSource, TKey>(
Expression<Func<TSource, TKey>> ordering)
{
return dataContext.GetTable<TSource>()
.OrderBy(ordering)
.ToList();
}
Now obviously that requires two type arguments, and you only want to specify one. 现在显然需要两个类型参数,而您只想指定一个。 There are various ways round this - basically you'd want to end up with a generic type and a method with one type argument (
TKey
) which can be inferred. 解决这个问题的方法有很多种-基本上,您希望得到一个通用类型和一个可以推断出一个类型参数(
TKey
)的方法。 For example: 例如:
var list = Orderer<ModelType>.Create(dataContext)
.OrderThisList(m => m.SomeProperty);
It's somewhat round-the-houses though considering that OrderBy
is already available... could you explain why you want this, and also what LINQ provider is involved? 考虑到
OrderBy
已经可用,这有点OrderBy
了……您能解释一下为什么OrderBy
,以及涉及到什么LINQ提供程序吗?
您应该使用内置的Linq方法var orderedList = myList.OrderBy(x => x.Username)
您不需要编写自己的扩展方法即可对列表进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.