如果要擴展LINQ查詢方法集,只需要為IEnumerable<T>擴展方法,
第一種:擴展聚合方法,類似已有的Max、Min,可以給具體型別擴展,也可以給泛型擴展,
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; namespace ConsoleApp4 { class Program { static void Main(string[] args) { var numbers1 = new double[]{ 1.9, 2, 8, 4, 5.7, 6, 7.2, 0 }; var query1 = numbers1.Median(); Console.WriteLine("double: Median = " + query1); var numbers2 = new int[] { 4, 5, 6, 8, 0 }; var query2 = numbers2.Median(); Console.WriteLine($"int:Median ={query2}"); var str1 = new string[] { "ab", "abc", "abcde", "abcedfs" }; ; var query3 = str1.Median(x => x.Length); Console.WriteLine($"string:{query3}"); } } public static class LINQExtension { public static double Median(this IEnumerable<double> source) { if(source.Count()==0) { throw new InvalidOperationException("無法計算中位數"); } var sortedList = source.OrderBy(x => x); int itemIndex = (int)sortedList.Count()/2; // 索引從0開始,itemIndex總是偏大 if(sortedList.Count()%2==0) { return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2; } else { return sortedList.ElementAt(itemIndex); } } //Int型別多載求中位數 public static double Median(this IEnumerable<int> source) { return source.Select(x => Convert.ToDouble(x)).Median(); } //泛型,需傳入選擇器 public static double Median<T>(this IEnumerable<T> source,Func<T,double> selector) { return source.Select(x => selector(x)).Median(); } } }View Code
第二中:擴展回傳集合的方法,類似Where、Orderby
public static class LINQExtension { public static IEnumerable<T> AlternateElements<T>(this IEnumerable<T> source) { List<T> list = new List<T>(); int i = 0; foreach (var item in source) { if (i % 4 == 2) { list.Add(item); } } return list; } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/64878.html
標籤:C#
上一篇:關于“Failed to complete setup of assembly(hr = 0x80131040). Probing terminated”
下一篇:事件的基本使用
