Linq案例
案例 LinQ
2023-09-27 14:24:30 时间
1.牛刀小试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace linq
{
class Program
{
static void Main(string[] args)
{
string[] words = { "hello","linq","good","wonderful"};
var shortWords = from word in words
where word.Length <= 5
select word;
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
Console.ReadKey();
}
}
}
2.Group分组处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace linq
{
class Program
{
static void Main(string[] args)
{
string[] words = { "hello","linq","good","wonderful","world","beautiful"};
//VAR 是3.5新出的一个定义变量的类型,其实也就是弱化类型的定义。VAR可代替任何类型,编译器会根据上下文来判断你到底是想用什么类型的。
var groups = from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups }; // 按长度将单词分组
foreach (var group in groups)
{
Console.WriteLine("Words of length" + group.Length);
foreach (string word in group.Words)
{
Console.WriteLine(" " + word);
}
}
Console.ReadKey();
}
}
}
3.XML 案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace linq
{
class Book
{
public string Publisher;
public string Title;
public int Year;
public Book(string title,string publisher,int year)
{
Title = title;
Publisher = publisher;
Year = year;
}
}
class Program
{
static void Main(string[] args)
{
Book[] books = new Book[]
{
new Book("Ajax","Zhang",2015),
new Book("Java","Li",2016),
new Book(".Net","Zhao",2016),
};
XElement xml = new XElement("books",
from book in books
where book.Year == 2016
select new XElement("book",
new XAttribute("title",book.Title),
new XElement("publisher",book.Publisher)
)
);
Console.WriteLine(xml);
Console.ReadKey();
}
}
}
相关文章
- c# Linq GroupBy数据分组,实现分组查询,带案例
- 【MATLAB教程案例23】基于MATLAB图像分割算法仿真——阈值分割法、Otsu阈值分割法、K均值聚类分割法等
- 数仓工具—Hive实战之自关联经典案例(11)
- 74 python - 打飞机案例(显示控制玩具飞机-面向对象)
- 经历3次阿里双11,2次京东618,我整理出50页性能瓶颈分析及案例总结
- 【力荐】Exadata火线救援:10TB级数据修复经典案例详解!
- 智慧城市数据安全防护如何开展?美国圣地亚哥案例探索
- SpringMVC+Mybatis实战案例
- 《微信小程序:开发入门及案例详解》—— 第2章 小程序开发核心 2.1 简介
- 测试职业困惑案例二:是坚持还是放弃?!
- Vue学习第28天——路由传参(query参数和params参数)详解及案例