1.Any操作符用来判断序列是否为空或者序列是否包含某个特定的值.
var list = new List<int>
{
1,2,3,
};
bool isEmpty = list.Any();
bool isHaveMoreThanTwo = list.Any(a => a > 2);
当Any用来判断集合中是否包含满足条件的指定元素时,在遇到第一个满足条件的元素时马上返回,不再判断集合后面的元素.
2.Contains. 用来判断集合中是否包含指定元素
var list = new List<int>
{
1,2,3,
};
var isHave = list.Contains(1);
Contains还有另一个重载方法叫做
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
如果List中保存的是自定义的对象,那么我们可以通过IEqualityComparer<T>接口来自定义一个相等比较规则.
比如:
class Person
{
public Int32 ID { get; set; }
public String FullName { get; set; }
}
class Student : Person
{
public String Major { get; set; }
}
自定义的比较规则(只要ID相同我们就认为这两个对象相同):
class StudentToPersonEquals : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x.ID == y.ID)
return true;
else
return false;
}
public int GetHashCode(Person obj)
{
return obj.GetHashCode();
}
}
var people = new List<Person>();
people.Add(new Student() { ID = 2, FullName = "Lisi" });
people.Add(new Student() { ID = 3, FullName = "Wangwu", Major = "Chemistry" });
people.Add(new Student() { ID = 4, FullName = "Zhaoliu", Major = "History" });
Console.WriteLine("People contains Zhangsan? {0}",
people.Contains(Zhangsan,new StudentToPersonEquals()));
3.从序列的开头返回指定个数的元素
返回序列的前三个元素
var list = Enumerable.Range(1, 10);
var ret = list.Take(3).Select(a=>a);
返回序列中前二个大于5的元素
var list = Enumerable.Range(1, 10);
var ret = list.Where(a => a > 5).Take(2);
4.Skip,跳过序列中指定数据的元素,然后返回剩余元素
跳过前二个元素,返回后8个元素
var list = Enumerable.Range(1, 10);
var ret = list.Skip(2);
把Skip和Take联合起来使用,可以实现分页效果
collection.Skip(currentPageIndex*ItemsInPage).Take(ItemsInPage)
5.Distinct,用来返回序列中的非重复元素
public class Person
{
public Int32 ID { get; set; }
public String FullName { get; set; }
}
public class PersonEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.ID == y.ID;
}
public int GetHashCode(Person obj)
{
return obj.ID;
}
}
List<Person> persons = new List<Person>();
persons.Add(new Person
{
FullName = "dd",
ID = 1,
});
persons.Add(new Person
{
FullName = "dd",
ID = 1,
});
persons.Add(new Person
{
FullName = "dd",
ID = 2,
});
var ret = persons.Distinct(new PersonEqualityComparer());
foreach (var item in ret)
{
Debug.WriteLine(item.ID);
}
聊一下关于IEqualityComparer接口实现,
如果要确定两个对象相等,就要保证它们的GetHashCode也要相同.