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
};