1. Aggregate(使用 Aggregate 创建数组的连乘,计算所有元素的总乘积。):
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
2. Aggregate重载(使用 Aggregate 创建一个流水账余额, 从最初余额 100 减去每次取出的金额,直到余额减少到 0 以下为止。):
double startBalance = 100.0;
int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
double endBalance =
attemptedWithdrawals.Aggregate(startBalance,
(balance, nextWithdrawal) =>
( (nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance ) );
3. SequenceEqual(使用 SequenceEquals 查看两个序列中所有元素是否以相同顺序匹配。):
var wordsA = new string[] { "cherry", "apple", "blueberry" };
var wordsB = new string[] { "cherry", "apple", "blueberry" };
bool match = wordsA.SequenceEqual(wordsB);
4. SequenceEqual重载(自定义比较方法):
List<Student> list = new List<Student>();
List<Student> list2 = new List<Student>();
Student a = new Student
{
UserId = 1,
StudentName = "Eric"
};
Student b = new Student
{
UserId = 1,
StudentName = "Eric"
};
Student c = new Student
{
UserId = 2,
StudentName = "laoyi"
};
list.Add(a);
list.Add(b);
list.Add(c);
list2.Add(c);
list2.Add(b);
list2.Add(a);
var tt = list.SequenceEqual(list, new StudentComparer());
public class Student
{
public int UserId { get; set; }
public string StudentName { get; set; }
}
自定义的比较类:
public class StudentComparer : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.UserId.Equals(y.UserId);
}
public int GetHashCode(Student obj)
{
return obj.UserId.GetHashCode();
}
}
5. join in (左外部联接和复合键,使用匿名类型封装多个键值):
List<Customer> customers = GetCustomerList();
List<Supplier> suppliers = GetSupplierList();
var supplierCusts =
from sup in suppliers
join cust in customers on new { sup.City, sup.Country } equals new { cust.City, cust.Country } into cs
from c in cs.DefaultIfEmpty() //移除 DefaultIfEmpty 方法调用可以使之成为内部联接
orderby sup.SupplierName
select new { Country = sup.Country,
City = sup.City,
SupplierName = sup.SupplierName,
CompanyName = c == null ? "(No customers)" : c.CompanyName
};