Linq一些简单的用法
一.摘要
很多人都开始使用LINQ ,代码看起来会很优雅。
二.前言
这里简单的记录几种常用的LINQ 方法。
三 案例
// 查询长度大于2的字符
string[] values = { "巧巧", "李四", "林三哥", "王五" };
var value = from v in values where v.Length > 2 select v;
foreach (var item in value)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------------------------");
//检索包含王得字符
var str = from v in values
where v.IndexOf("王") > -1
select v;
foreach (var item in str)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------------------------");
ArrayList gList = new ArrayList();
gList.Add(
new GuestInfo { Name = "林晚荣", Age = 22, Tel = "88888888" }
);
gList.Add(
new GuestInfo { Name = "宁雨昔", Age = 36, Tel = "55555555" }
);
var query = from GuestInfo guest in gList
where guest.Age > 19
select guest;
foreach (GuestInfo item in query)
{
Console.WriteLine(item.Name, item.Age, item.Tel);
}
Console.WriteLine("--------------------------------------------");
List<GuestInfo> glists = new List<GuestInfo>()
{
new GuestInfo{
Name = "林晚荣",
Age=21,
TelTable = new List<string>()
{
"026-88888888",
"13888888888"
}
}
};
//查询13888888888
var querys = from guest in glists
from tel in guest.TelTable
where tel.IndexOf("13888888888") > -1
select guest;
foreach (var item in querys)
{
Console.WriteLine(item.Name, item.Age);
foreach (var table in item.TelTable)
{
Console.WriteLine(table);
}
}
string[] values = { "巧巧", "李四", "林三哥", "王五" };
var value = from v in values where v.Length > 2 select v;
foreach (var item in value)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------------------------");
//检索包含王得字符
var str = from v in values
where v.IndexOf("王") > -1
select v;
foreach (var item in str)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------------------------");
ArrayList gList = new ArrayList();
gList.Add(
new GuestInfo { Name = "林晚荣", Age = 22, Tel = "88888888" }
);
gList.Add(
new GuestInfo { Name = "宁雨昔", Age = 36, Tel = "55555555" }
);
var query = from GuestInfo guest in gList
where guest.Age > 19
select guest;
foreach (GuestInfo item in query)
{
Console.WriteLine(item.Name, item.Age, item.Tel);
}
Console.WriteLine("--------------------------------------------");
List<GuestInfo> glists = new List<GuestInfo>()
{
new GuestInfo{
Name = "林晚荣",
Age=21,
TelTable = new List<string>()
{
"026-88888888",
"13888888888"
}
}
};
//查询13888888888
var querys = from guest in glists
from tel in guest.TelTable
where tel.IndexOf("13888888888") > -1
select guest;
foreach (var item in querys)
{
Console.WriteLine(item.Name, item.Age);
foreach (var table in item.TelTable)
{
Console.WriteLine(table);
}
}
出处:http://www.cnblogs.com/liuyong/
作者喜欢研究 Sql Server ,ASP.NET MVC , Jquery WCF 等技术,同时关心分布式架构的设计应用。转载请保留原文链接,谢谢!