linq用简单的英语 [英] linq in plain english

查看:95
本文介绍了linq用简单的英语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以用简单的英语解释这个语法吗

Can someone explain in plain english the syntax of this:

这是OrderBy运算符的签名:

OrderedSequence<TElement> OrderBy<TElement, TKey>(
    this IEnumerable<TElement> source, 
    Func<TElement, TKey> keySelector
)

这表明您需要提供给OrderBy的委托的类型是Func<TElement, TKey>.

This shows that the type of the delegate you need to provide to OrderBy is Func<TElement, TKey>.

我正在寻找一个函数,该函数接收一个列表和一个字符串作为参数(列名),并且我陷入了OrderBy扩展方法的语法中. Func<...>是什么意思?我应该在哪里放置字符串参数?

I'm looking to build a function that receives a list and a string as a parameter (the column name) and I'm stuck on the syntax of the OrderBy extension method. What does Func<...> mean? Where do I put the string parameter to sort with?

谢谢.

推荐答案

在给定的条件下,您可能会在实践中看到它

Here's how you might see it in practice, given

List<MyClass> list;

public class MyClass
{
    public string Name { get; set; }
    // ...
}

你可能会说

list.OrderBy(x => x.Name);

我们知道如何将this IEnumerable<TElement> source称为任何IEnumerable的扩展方法.

The this IEnumerable<TElement> source is how we know that we call this as an extension method off of any IEnumerable.

如果您使用动态属性名称,那么您将不得不变得更加花哨.我首先定义一个辅助函数,以确保我们的lambda不会太凌乱.请注意,为了时间和概念的清晰性,我省略了一些检查和错误处理之类的东西:

If you're using a dynamic property name, you're going to have to get more fancy. I'd first define a helper function to make sure our lambda doesn't get too messy. Note that for the sake of time and clarity to the concept being demonstrated, I've omitted some things like checks and error handling:

public object GetPropertyByName(object obj, string propertyName)
{
    object result = null;

    var prop = obj.GetType().GetProperty(propertyName);
    result = prop.GetValue(obj, null);

    return result;

}

现在使用我们的助手如下:

Now use our helper as follows:

List<MyClass> list = new List<MyClass>();
list.Add(new MyClass { Name = "John" });
list.Add(new MyClass { Name = "David" });
list.Add(new MyClass { Name = "Adam" });
list.Add(new MyClass { Name = "Barry" });

const string desiredProperty = "Name"; // You can pass this in
var result = list.OrderBy(x => GetPropertyByName(x, desiredProperty));
foreach (MyClass c in result)
{
    Console.WriteLine(c.Name);
}

这篇关于linq用简单的英语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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