LINQ函数

时间:2024-04-12 10:04:42

LINQ函数虽然和LINQ语句实现了同样的功能,但LINQ函数使用起来更加快捷。学过数据库的感觉LINQ语句都不难,但语句比较长。

会LINQ函数,才算会LINQ。

1、Where(),结果过滤

 List<int> list = new List<int>() {,,,,,,,,, };
IEnumerable<int> newList = list.Where(a => a >= );
//查找大于3的数
//输出
foreach (var item in newList)
{
Console.WriteLine(item);
}

结果:

2、Select()

Select()处理结果会传回一个对象,这个对象可以是现在对象 ,也可以是匿名类型。

在LINQ语句 中的select new语句 ,会自动被编译器转换为Select().

有如下代码:

 List<int> list = new List<int>() {,,,,,,,,, };
var Num = from aa in list
where aa ==
select new
{
Number = aa,
};
Console.WriteLine(Num.FirstOrDefault().Number);
 var SelectNum = list.Where(x => x == ).Select(x => new
{
Number = x
});

上面两段代码其实是一样的。

 3、SelectMany()

SelectMany()类似于数据库中的CrossJoin

 List<int> list1 = new List<int>() { , , , , ,  };
List<int> list2 = new List<int>() { , , , , , };
 var query = list1.SelectMany(x => list2);
foreach (var item in query)
{
Console.WriteLine(item);
}

运行结果就是将list2输出6次

下面来看看MSDN上面的代码

class PetOwner
{
public string Name { get; set; }
public List<String> Pets { get; set; }
} public static void SelectManyEx1()
{
PetOwner[] petOwners =
{ new PetOwner { Name="Higa, Sidney",
Pets = new List<string>{ "Scruffy", "Sam" } },
new PetOwner { Name="Ashkenazi, Ronen",
Pets = new List<string>{ "Walker", "Sugar" } },
new PetOwner { Name="Price, Vernette",
Pets = new List<string>{ "Scratches", "Diesel" } } }; // Query using SelectMany().
IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets); Console.WriteLine("Using SelectMany():"); // Only one foreach loop is required to iterate
// through the results since it is a
// one-dimensional collection.
foreach (string pet in query1)
{
Console.WriteLine(pet);
}
}

运行结果:

Using SelectMany():
Scruffy
Sam
Walker
Sugar
Scratches
Diesel

这里其实很好理解 。就是1对2,输出2.

4、GroupBy()

GroupBy()会按照给定的key(keySelector)以及内容elementSelector,产生群组后的结果

GroupBy()设置了使用数列本身作为Key值,并且利用这个Key分组产生分组的数据。

 List<int> list = new List<int>() { , , , , , ,  };

             var query = list.GroupBy(x => x);

             foreach (var item in query)
{
Console.WriteLine("NUMBER:{0} COUNT{1}",item.Key,item.Count());
}

运行结果:

NUMBER:1 COUNT2
NUMBER:2 COUNT1
NUMBER:3 COUNT1
NUMBER:4 COUNT1
NUMBER:5 COUNT2

 foreach (var item in query)
{
for (int i = ; i < item.Count(); i++)
{
Console.WriteLine(item.ElementAt(i));
}
Console.WriteLine("=======================");
}

运行结果:

=======================

=======================

=======================

=======================

=======================

 5、ToLookUp()

从 IEnumerable<T> 生成一个泛型 Lookup<TKey, TElement>。

ToLookUp()看起来和GroupBy()有些类似,但是它会另外生成一个新的集合对象,这个集合对象由ILookup<TKey,TElement>组成

 var Marks = new[]
{
new {Mark = ,Group = "A"},
new {Mark = ,Group = "B"},
new {Mark = ,Group = "C"},
new {Mark = ,Group = "D"}
}; var lookUpValue = Marks.ToLookup(x => x.Group); foreach (var item in lookUpValue)
{
Console.WriteLine("========Group:{0}=============",item.Key);
foreach (var result in item)
{
Console.WriteLine(result.Group + " " + result.Mark);
}
}

运行结果

========Group:A=============
A 90
========Group:B=============
B 80
========Group:C=============
C 70
========Group:D=============
D 60

另一段测试代码:

  var MarksWithName = new[]
{
new {Mark = ,Name="Jack",Group="A"},
new {Mark = ,Name="Jany",Group="B"},
new {Mark = ,Name = "Tom",Group="C"}
}; var lookUpValue2 = MarksWithName.ToLookup(x => x.Group);
foreach (var item in lookUpValue2)
{
Console.WriteLine("============Group:{0}==============",item.Key);
foreach (var result in item)
{
Console.WriteLine("Name:{0} Mark:{1}",result.Name,result.Mark);
}
}

运行结果:

============Group:A==============
Name:Jack Mark:90
============Group:B==============
Name:Jany Mark:80
============Group:C==============

6、Join

将两个集合进行联接,即数据库中的Inner Join

 var Mark = new[]
{
new {Name = "C",Mark = },
new {Name = "A",Mark = },
new {Name = "B", Mark = } }; var Age = new[]
{
new {Name = "B",Age = },
new {Name = "C",Age = },
new {Name = "A",Age = }
};
//LINQ语句
var query = from mk in Mark
join ae in Age on mk.Name equals ae.Name
select
new
{
Name = mk.Name,
Mark = mk.Mark,
Age = ae.Age
}; //输出
foreach (var item in query)
{
Console.WriteLine("姓名{0} 成绩{1} 年龄{2}",item.Name,item.Mark,item.Age);
}
 //LINQ函数

             var query2 = Mark.Join(Age, mk => mk.Name, ae => ae.Name, (mk, ae) => new { Name = mk.Name,Mark = mk.Mark,Age = ae.Age });

             foreach (var item in query2)
{
Console.WriteLine("姓名{0} 成绩{1} 年龄{2}", item.Name, item.Mark, item.Age);
}

上面两段代码输出的结果都是:

姓名C 成绩65 年龄17
姓名A 成绩70 年龄20
姓名B 成绩80 年龄18

7、GroupJoin

将两个集合进行联接,并对结果进行分组。下面的例子就是以国家名字为组,显示其对应的省份信息。

    class Country
{
public string CountryName { get; set; }
} class Province
{
public Country OwnerCountry { get; set; }
public string ProvinceName { get; set; }
public string ProvinceSize { get; set; }
public string ProvinceSpot { get; set; }
}
             Country c1 = new Country()
{
CountryName = "China"
}; Country c2 = new Country()
{
CountryName = "America"
}; Country c3 = new Country()
{
CountryName = "Korea"
}; Country c4 = new Country()
{
CountryName = "Russian"
}; Province p1 = new Province()
{
ProvinceName = "Hunan",
ProvinceSize = "",
ProvinceSpot = "Old City",
OwnerCountry = c1
}; Province p2 = new Province()
{
ProvinceName = "Chicago",
ProvinceSize = "",
ProvinceSpot = "Linkin Park",
OwnerCountry = c2
}; Province p3 = new Province()
{
ProvinceName = "Seoul",
ProvinceSize = "",
ProvinceSpot = "Tian Tian World",
OwnerCountry = c3,
}; Province p4 = new Province()
{
ProvinceName = "Hunan",
ProvinceSize = "",
ProvinceSpot = "Tian Meng Mountain",
OwnerCountry = c1
}; Province p5 = new Province()
{
ProvinceName = "Moscow",
ProvinceSize = "",
ProvinceSpot = "Moscow University",
OwnerCountry = c4
}; Province p6 = new Province()
{
ProvinceName = "Moscow",
ProvinceSize = "",
ProvinceSpot = "HelloWorld",
OwnerCountry = c4
};

声明4个Country类和6个Province类,并放入countries和provinces集合

             List<Province> provinces = new List<Province>()
{
p1,p2,p3,p4,p5,p6
}; List<Country> countries = new List<Country>()
{
c1,c2,c3,c4
};

先来看看Join的结果 

  var joinResult = countries.Join(provinces,
country => country,
province => province.OwnerCountry,
(country, province) =>
new
{
CountryName = country.CountryName,
ProvinceName = province.ProvinceName,
Size = province.ProvinceSize,
Spot = province.ProvinceSpot,
});
Console.WriteLine("--------------------------------");
foreach (var item in joinResult)
{
Console.WriteLine(item.CountryName + " " + item.ProvinceName + " " + item.Size + " " + item.Spot);
}

运行结果:

--------------------------------
China Hunan 200 Old City
China Hunan 200 Tian Meng Mountain
America Chicago 150 Linkin Park
Korea Seoul 100 Tian Tian World
Russian Moscow 80 Moscow University
Russian Moscow 80 HelloWorld
--------------------------------

再看看GroupJoin的结果

   var groupJoinResult = countries.GroupJoin(provinces,
country=>country,
province=>province.OwnerCountry,
(country,province)=>
new
{
Name = country.CountryName,
ProvinceSet = province.Select(x=>x)
});
foreach (var item in groupJoinResult)
{
Console.WriteLine("******************");
Console.WriteLine(item.Name);
foreach (var p in item.ProvinceSet)
{
Console.WriteLine(p.ProvinceName + " " + p.ProvinceSize + " " + p.ProvinceSpot);
}
}

运行结果:

******************
China
Hunan 200 Old City
Hunan 200 Tian Meng Mountain
******************
America
Chicago 150 Linkin Park
******************
Korea
Seoul 100 Tian Tian World
******************
Russian
Moscow 80 Moscow University
Moscow 80 HelloWorld

8、Distinct

去除集合中的重复结果

值类型

 class Program
{
static void Main(string[] args)
{
List<int> valueList = new List<int>() { , , , , , , , , };
var distinctValueList = valueList.Distinct().ToList();
distinctValueList.ForEach(x => Console.WriteLine(x));
}
}

运行结果

引用类型

 public class PrintImage
{
public int ImageKey { get; set; } public string ImagePath { get; set; }
} //定义方法以支持对象的相等比较。
//https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.iequalitycomparer-1?redirectedfrom=MSDN&view=netframework-4.8
class PrintImageEqualityComparer : IEqualityComparer<PrintImage>
{
public bool Equals(PrintImage p1, PrintImage p2)
{
if (p1 == null && p2 == null)
return true;
else if (p1 == null || p2 == null)
return false;
else if (p1.ImageKey == p2.ImageKey)
return true;
else
return false;
} public int GetHashCode(PrintImage pImage)
{
return pImage.ImageKey.GetHashCode();
}
} class Program
{
static void Main(string[] args)
{
List<PrintImage> objList = new List<PrintImage>()
{
new PrintImage()
{
ImageKey = ,
ImagePath = "D:\\crawler\\image1"
},
new PrintImage()
{
ImageKey = ,
ImagePath = "D:\\crawler\\image2"
},
new PrintImage()
{
ImageKey = ,
ImagePath = "D:\\crawler\\image3"
},
new PrintImage()
{
ImageKey = ,
ImagePath = "D:\\crawler\\image4"
}
}; //使用实现了IEqualityComparer<T>的PrintImageEqualityComparer类对PrintImage对象进行比较
//通过使用Distincet去除了集合中的第二个对象
var distinctObjList = objList.Distinct(new PrintImageEqualityComparer()).ToList();
distinctObjList.ForEach(x => { Console.WriteLine(x.ImageKey); Console.WriteLine(x.ImagePath); });
}
}

运行结果:

D:\crawler\image1

D:\crawler\image3

D:\crawler\image4