C# 使用Linq或Lambda“;选择";哪种方法作为参数
我有下面的代码,但我不知道如何使用“Select”关键字使lambda表达式绑定到字符串列表。 但是如果我要调用的方法有2个或更多的参数 我的问题是如何生成lambda表达式C# 使用Linq或Lambda“;选择";哪种方法作为参数,c#,linq,lambda,C#,Linq,Lambda,我有下面的代码,但我不知道如何使用“Select”关键字使lambda表达式绑定到字符串列表。 但是如果我要调用的方法有2个或更多的参数 我的问题是如何生成lambda表达式 //this code below is error //List<TwoWords> twoWords = stringlist.Select(CreateTwoWords(1,2)) // .ToList(); class Program
//this code below is error
//List<TwoWords> twoWords = stringlist.Select(CreateTwoWords(1,2))
// .ToList();
class Program
{
public class TwoWords
{
public string word1 { get; set; }
public string word2 { get; set; }
public void setvalues(string words)
{
word1 = words.Substring(0, 4);
word2 = words.Substring(5, 4);
}
public void setvalues(string words,int start, int length)
{
word1 = words.Substring(start, length);
word2 = words.Substring(start, length);
}
}
static void Main(string[] args)
{
List<string> stringlist = new List<string>();
stringlist.Add("word1 word2");
stringlist.Add("word3 word4");
//i called createTwoWords with 1 parameter
List<TwoWords> twoWords = stringlist.Select(CreateTwoWords)
.ToList();
//i was confused how to make lamda experesion to call method with parameter 2 or more
//this code below is error
//List<TwoWords> twoWords = stringlist.Select(CreateTwoWords(1,2)).ToList();
}
private static TwoWords CreateTwoWords(string words)
{
var ret = new TwoWords();
ret.setvalues(words);
return ret;
}
private static TwoWords CreateTwoWords(string words, int start, int length)
{
var ret = new TwoWords();
ret.setvalues(words, start, length);
return ret;
}
}
//下面的代码是错误的
//List twoWords=stringlist.选择(CreateTwords(1,2))
//.ToList();
班级计划
{
公开课二字
{
公共字符串word1{get;set;}
公共字符串word2{get;set;}
公共void设置值(字符串字)
{
word1=words.Substring(0,4);
word2=words.Substring(5,4);
}
公共void集合值(字符串字、整数开始、整数长度)
{
word1=words.Substring(开始,长度);
word2=words.Substring(开始,长度);
}
}
静态void Main(字符串[]参数)
{
List stringlist=新列表();
stringlist.添加(“word1 word2”);
stringlist.添加(“第3字第4字”);
//我用1个参数调用了CreateTowwords
List twoWords=stringlist.选择(CreateTwords)
.ToList();
//我不知道如何使lamda expresion调用参数为2或更多的方法
//下面的代码是错误的
//List twowwords=stringlist.Select(createtwowwords(1,2)).ToList();
}
私有静态TwoWords CreateTwords(字符串字)
{
var ret=新的两个单词();
ret.setvalues(文字);
返回ret;
}
私有静态TwoWords CreateTwords(字符串字、int开始、int长度)
{
var ret=新的两个单词();
ret.setvalues(字、开始、长度);
返回ret;
}
}
这就是您所需要的:
stringlist.Select(str => CreateTwoWords(str, 1, 2)).ToList();
基本上,创建一个新的lambda(Func
),以您喜欢的方式调用函数。这就是您所需要的:
stringlist.Select(str => CreateTwoWords(str, 1, 2)).ToList();
基本上,创建一个新的lambda(
Func
),以您喜欢的方式调用函数。谢谢您的帮助,我仍然是lambda表达式的新手。谢谢您的帮助,我仍然是lambda表达式的新手。