扩展/方法中的 C# Linq
您好,
我正在寻找创建一个包括 linq 查询的扩展方法。 我正在寻找的是一种方法或扩展方法,可以执行类似这样的操作
var orderedList = OrderThisList<ModelName>(List<T> sourceList, //and something like m=>m.Username);
,其中 ModelName 是实体,Username 是我想要订购的字段。 该方法看起来像
public List<T> OrderThisList<T>(//some linq property?)
{
//What code goes here?
}
Greetings
I'm looking for creating a extension method including a linq query.
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.
The method would look something like
public List<T> OrderThisList<T>(//some linq property?)
{
//What code goes here?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:目前还非常不清楚这个问题的全部内容,但听起来我们正在处理内存中的集合而不是 LINQ to SQL 等。
如果使用
OrderBy< 的问题/code> 的缺点是它不会就地对列表进行排序,您应该使用
List.Sort()
,可能会传入自定义比较器。我的 MiscUtil 项目有一些可以帮助您的帮助程序类型。例如:
如果您使用 LINQ to SQL 并且有 数据上下文,您可以使用:
现在显然需要两个类型参数,而您只想指定一个。有多种方法可以解决这个问题 - 基本上,您希望最终得到一个泛型类型和一个带有可以推断的一个类型参数(
TKey
)的方法。例如:虽然考虑到
OrderBy
已经可用,但它有点绕房子...您能解释一下为什么需要这个,以及涉及什么 LINQ 提供程序吗?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.
If the problem with using
OrderBy
is that it doesn't sort the list in-place, you should be usingList<T>.Sort()
, possibly passing in a custom comparator.My MiscUtil project has a few helper types which may help you. For example:
If you're using LINQ to SQL and you've got a data context, you could use:
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. For example: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?您应该使用内置的 Linq 方法
varorderedList = myList.OrderBy(x => x.Username)
您不需要编写自己的扩展方法来对列表进行排序。You should use the built in Linq method
var orderedList = myList.OrderBy(x => x.Username)
You shouldn't need to write your own extension method to sort a list.