Linq 使用Lamba表达式从对象属性创建字符串

Linq 使用Lamba表达式从对象属性创建字符串,linq,c#-4.0,lambda,Linq,C# 4.0,Lambda,这与我的问题有关,但这更多的是我试图理解的一部分的抽象。我真的很难让我的大脑理解这个概念 给定这样定义的对象: public class item { public int itemId { get; set; } public string itemName { get; set; } public string itemDescription { get; set; } } 和一个IEnumerable foo 假设我想写一个扩展方法,使表达式 foo.GetFul

这与我的问题有关,但这更多的是我试图理解的一部分的抽象。我真的很难让我的大脑理解这个概念

给定这样定义的对象:

public class item
{
    public int itemId { get; set; }
    public string itemName { get; set; }
    public string itemDescription { get; set; }
}
和一个
IEnumerable foo

假设我想写一个扩展方法,使表达式

foo.GetFullDescription(x => x.itemId.ToString() + "(" + x.itemName + ")")
将等于包含Lambda表达式中定义的连接项的
IEnumerable
。例如,如果我的
foo
对象正好包含一个
对象,如下所示:

{
fooItem.itemId = 1
fooItem.itemName = "foo"
fooItem.itemDescription = "fooDescription"
}
。。。我给扩展方法的结果分配了一个变量,如下所示:

var bar = foo.GetFullDescription(x => x.itemId.ToString() + "(" + x.itemName + ")");
。。。我将把
bar
变成一个
IEnumerable
,其中有一个项目,该项目将等于
1(foo)

我将如何编写扩展方法?第一部分相对简单:

public static IEnumerable<string> GetFullDescription(this IEnumerable<item> target, <some expression?> expr){


}
公共静态IEnumerable GetFullDescription(此IEnumerable目标,expr){
}
我们将非常感谢您的帮助。非常感谢您的简单解释。

根据您的描述(如果我读对了),您似乎只需要使用Select

var itemsAsStrings = foo.Select(x => x.itemId.ToString() + "(" + x.itemName + ")");

下面是LINQPad的一个工作示例。只要把它抄过去就行了

void Main()
{
    System.Console.WriteLine(GetFullDescription(new Item(){itemId = 2, itemName="two"}, 
    x => x.itemId.ToString() + "(" + x.itemName + ")"));
}

public delegate string Lambda (Item item);

public class Item
{
    public int itemId { get; set; }
    public string itemName { get; set; }
    public string itemDescription { get; set; }
}

// Define other methods and classes here
public static string GetFullDescription(Item item, Lambda lambda){
    return lambda(item);
}
您只需声明一个委托,该委托返回一个字符串,可以调用任意函数,并接受一个Item参数。记住,委托基本上是一个函数变量,如果您定义了函数的输入和输出。我认为这是你的完整扩展方法

public delegate string Lambda (Item item);
public static string GetFullDescription(this IEnumerable<Item> items, Lambda lambda){
    foreach(var item in items){
         return yield lambda(item); 
    }
}
公共委托字符串Lambda(项);
公共静态字符串GetFullDescription(此IEnumerable items,Lambda Lambda){
foreach(项目中的var项目){
收益率λ(项目);
}
}

有很多方法可以完成这项任务,我真正想要的是学习如何使用Linq表达式来完成这项任务,这样我就可以更普遍地应用这个想法。嗯。。。这看起来与我要查找的内容方向正确,但与
类相关。我会看看我是否能用泛型来处理这个问题。我能用泛型的方式来使用它。太棒了,比我想象的要简单得多。非常感谢!