LINQ 五 ------使用LINQ进行匿名对象初始化
-
- [6.2 匿名类型](#6.2 匿名类型)
6.2 匿名类型
可以不用声明定义一个对象,直接使用new,然后直接赋值即可
csharp
string[] names = { "Tom", "Jerry", "kate", "Lucy", "Micky", "li" };
var query =
from n in names
select new
{
name = n,
liName = n.ToLower()
};
foreach (var item in query)
{
Console.WriteLine(item.liName+","+item.name);
}
Console.WriteLine("--------------");
IEnumerable<string> strName =
from n in query
where n.name.Length > 2
orderby n.name.Length descending
select n.name + "," + n.liName;
foreach (var item in strName)
{
Console.WriteLine(item);
}
//输出
tom,Tom
jerry,Jerry
kate,kate
lucy,Lucy
micky,Micky
li,li
--------------
Jerry,jerry
Micky,micky
kate,kate
Lucy,lucy
Tom,tom
使用两个数组,分别取出两个数组元素的索引,进行比较,然后拼接成一个匿名对象,进行输出。
csharp
string[] names = { "Tom", "Jerry", "kate", "Lucy", "Micky", "li" ,"zh"};
int[] ages = { 10, 20, 50, 12, 45, 20 };
var indexedItems = names.Select((value, index) => new { Index = index, Value = value });
var dicar =
from n in names.Select((value, index) => new { Index = index, Value = value })
join a in ages.Select((value, index) => new { Index = index, Value = value }) on n.Index equals a.Index
select new
{
name = n.Value,
age = a.Value
};
foreach (var item in dicar)
{
Console.WriteLine($"{item.name},{item.age}");
}
//输出
Tom,10
Jerry,20
kate,50
Lucy,12
Micky,45
li,20