2.投影操作符
Select
作用:从某种类型的元素组成的输入序列创建一个由其他类型的元素组成的输出序列。
输入的类型和输出的类型不必相同。
原型
public static IEnumerable<S> Select<T, S>(
this IEnumerable<T> source,
Func<T, S> selector);
public static IEnumerable<S> Select<T, S>(
this IEnumerable<T> source,
Func<T, int, S> selector);
例子
static void Main(string[] args)
{
string[] items = { "csharp", "vb", "java", "cpp", "python","php","c++" };
var result = items.Select<string, int>(c => c.Length);
//显示查询结果
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.Read();
}
结果
static void Main(string[] args)
{
string[] items = { "csharp", "vb", "java", "cpp", "python","php","c++" };
var result = items.Select<string,string>((c, i) => "" + (i + 1) + ":" + c);
//显示查询结果
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.Read();
}
结果
SelectMany
作用:操作符可以基于输入序列创建一个一到多的输出投影序列。Select操作符可以为
每个输入元素返回一个输出元素,而SelectMany可以为每个输入元素返回空或多个输出
元素。
原型
public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, IEnumerable<S>> selector);
public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, int, IEnumerable<S>> selector);
例子
static void Main(string[] args)
{
string[] items = { "Hello World", "Welcome to MVC", "Linq to Sql"};
var result = items.SelectMany(c => c.Split(' '));
//显示查询结果
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.Read();
}
结果
static void Main(string[] args)
{
string[] items = { "Hello World", "Welcome to MVC", "Linq to Sql"};
var result = items.SelectMany((c, i) => c.Split(' ').Select(p => new { id = i + 1,msg = p});
//显示查询结果
foreach (var item in result)
{
Console.WriteLine(item.id + ":" + item.msg);
}
Console.Read();
}
结果




浙公网安备 33010602011771号