版权声明:欢迎大家留言讨论共同进步,转载请注明出处 https://blog.csdn.net/qq_39108767/article/details/86648448
首先是官方文档:
https://docs.microsoft.com/zh-cn/dotnet/api/system.linq?view=netframework-4.7.2
https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable?view=netframework-4.7.2
合理的使用System.Linq 类库,可以让代码更加高效简洁,对操作继承IEnumerable的数据类型(数组、List、Dictionary等)可以快速高效的做一些操作,比如在字典中根据Value值获取对应的Key,常规方法就是遍历比较,引用Linq库的话,则有一下几种方法:
Dictionary<string, int> dic = new Dictionary<string, int>();
for (int i = 0; i < 10; i++)
{
dic.Add("string_" + i, i);
}
//获取第一个符合条件的Key
//没有符合条件Key, 返回null
string firstKey = dic.FirstOrDefault(pair => pair.Value == 20).Key;
//获取所有符合条件的Key
//没有符合条件Key, 返回空List
List<string> keys01 = dic.Where(pair => pair.Value == 20).Select(pair => pair.Key).ToList();
//获取所有符合条件的Key
List<string> keys02 = (from pair in dic where pair.Value == 7 select pair.Key).ToList();
以下是System.Linq 的部分Api的测试代码,详情及全部的Api可以到官方文档中查看
public void LinqFuncTest()
{
//https://docs.microsoft.com/zh-cn/dotnet/api/system.linq?view=netframework-4.7.2
//https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable?view=netframework-4.7.2
string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
List<string> fruitList = fruits.ToList();
List<int> numList = new List<int>() { 0, 1, 2, 3, 4 };
//Aggregate 01
//对序列应用累加器函数 将指定的种子值用作累加器初始值 并使用指定的函数选择结果值
//public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector);
//Aggregate 02
//对序列应用累加器函数 将指定的种子值用作累加器初始值
//public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);
//Aggregate 03
//对序列应用累加器函数
//public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func);
//TSource : source的元素类型
//TAccumulate : 累加器值的类型
//TResult : 结果值的类型
//source IEnumerable<TSource> : 要应用累加器的序列IEnumerable<T>
//seed TAccumulate : 累加器的初始值
//func Func<TAccumulate, TSource, TAccumulate> : 要对每个元素调用的累加器函数
//resultSelector Func<TAccumulate, TResult> : 将累加器的最终值转换为结果值的函数
//Aggregate 01 Demo 查找长度最长的字符串
string longestName =
fruits.Aggregate("banana", (longest, next) => next.Length > longest.Length ? next : longest, fruit => fruit.ToUpper());
Debug.Log("longestName : " + longestName);
//Aggregate 02 Demo 查找偶数的数量
int numEven = fruits.Aggregate(0, (total, next) => next.EndsWith("e") ? total + 1 : total);
Debug.Log("numEven : " + numEven);
//Aggregate 03 Demo 颠倒字符串顺序
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words.
string[] words = sentence.Split(' ');
// Prepend each word to the beginning of the new sentence to reverse the word order.
string reversed = words.Aggregate((workingSentence, next) => next + " " + workingSentence);
Debug.Log("reversed : " + reversed);
//-----
//All
//是否序列中的所有元素都满足条件
//public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
//Any
//是否序列中存在任意元素, 即序列不为空
//public static bool Any<TSource>(this IEnumerable<TSource> source);
//Any
//是否序列中存在任意元素满足条件
//public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
//source IEnumerable<TSource> : IEnumerable<T>序列
//predicate Func<TSource, Boolean> : 用于测试每个元素是否满足条件的函数
bool allStartWithB = fruits.All(name => name.StartsWith("m"));
Debug.Log("allStartWithB " + allStartWithB);
bool hasElements = fruits.Any();
Debug.Log("hasElements " + hasElements);
bool unvaccinated = fruits.Any(name => name.StartsWith("m"));
Debug.Log("unvaccinated " + unvaccinated);
//-----
//Append
//将一个值追加到序列末尾
//public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element);
Debug.Log(fruitList.Count + " " + fruitList.Append("newFruit").ToList().Count);
//-----
//AsEnumerable
//转化数据类型为IEnumerable<T>
//public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source);
IEnumerable<int> intIE = numList.AsEnumerable();
//-----
//Average
//计算数值序列的平均值
//例:public static float Average(this IEnumerable<float> source);
//-----
//Cast
//将IEnumerable的元素强制转换为指定的类型
//public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source);
List<string> strList = numList.Cast<string>().ToList();
//-----
//Concat
//连接两个序列
//public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
//连接数组和List
IEnumerable<string> strIE = fruits.Concat(fruitList);
//-----
//Contains
//序列是否包含指定的元素
//public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value);
//public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
//可以在参数中加入自定义的比较器(重写Equals)
bool b = fruits.Contains("mango");
//-----
//Count
//返回序列中的元素数量
//public static int Count<TSource>(this IEnumerable<TSource> source);
//返回序列中满足条件的元素数量
//public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
int count = fruitList.Count(f => f.StartsWith("m"));
//-----
//DefaultIfEmpty
//返回IEnumerable<T>的元素 如果序列为空,则返回一个具有默认值/指定值的序列
//public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source);
//public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue);
IEnumerable<string> strIE2 = fruitList.DefaultIfEmpty("defaultValue");
//-----
//ElementAt
//返回序列中指定索引处的元素
//public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index);
int age = numList.ElementAt(1);
//ElementAtOrDefault
//返回序列中指定索引处的元素 如果索引超出范围,则返回默认值
//public static TSource ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index);
age = numList.ElementAtOrDefault(100);
//-----
//Empty
//返回具有指定类型参数的空IEnumerable<T>
//public static IEnumerable<TResult> Empty<TResult>();
IEnumerable<string> empty = Enumerable.Empty<string>();
//-----
//Distinct
//返回序列中的非重复元素 使用默认/自定义的相等比较器对值进行比较
//public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);
//public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);
IEnumerable<int> distinctAges = numList.Distinct();
//-----
//Except
//生成两个序列的差集 (在first中但不在second中, second有但first中没有的值不会被返回) 使用默认/自定义的相等比较器对值进行比较
//public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
//public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);
int[] numbers2 = { 0, 2 };
IEnumerable<int> onlyInFirstSet = numList.Except(numbers2);
//-----
//First
//返回序列中的第一个元素/满足指定条件的第一个元素
//public static TSource First<TSource>(this IEnumerable<TSource> source);
//public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
//FirstOrDefault
//返回序列中的第一个元素/满足条件的第一个元素 如果未找到该元素,则返回默认值
//public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);
//public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
}