| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- namespace Assets.Plugins.CommonTool
- {
- public static class ListHelper
- {
- /// <summary>
- /// 自定义Distinct扩展方法
- /// </summary>
- /// <typeparam name="T">要去重的对象类</typeparam>
- /// <typeparam name="TC">自定义去重的字段类型</typeparam>
- /// <param name="source">要去重的对象</param>
- /// <param name="getField">获取自定义去重字段的委托</param>
- /// <returns></returns>
- public static IEnumerable<T> IwbDistinct<T, TC>(this IEnumerable<T> source, Func<T, TC> getField)
- {
- return source.Distinct(new Compare<T, TC>(getField));
- }
- /// <summary>
- /// 合并字典
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="first">字典1</param>
- /// <param name="second">字典2</param>
- /// <param name="isCover">字典2是否覆盖字典1,默认 true</param>
- /// <returns></returns>
- public static Dictionary<string, T> MergeDictionary<T>(this Dictionary<string, T> first, Dictionary<string, T> second ,bool isCover= true)
- {
- if (first == null) first = new Dictionary<string, T>();
- if (second == null) return first;
- foreach (string key in second.Keys)
- {
- if (first.ContainsKey(key))
- {
- if (isCover)
- {
- first[key] = second[key];
- }
- }
- else
- {
- first.Add(key, second[key]);
- }
- }
- return first;
- }
- /// <summary>
- /// 合并字典
- /// </summary>
- /// <param name="first">字典1</param>
- /// <param name="second">字典2</param>
- /// <param name="isCover">字典2是否覆盖字典1,默认 true</param>
- /// <returns></returns>
- public static Hashtable MergeHashtable(this Hashtable first, Hashtable second ,bool isCover= true)
- {
- if (first == null) first = new Hashtable();
- if (second == null) return first;
- foreach (string key in second.Keys)
- {
- if (first.ContainsKey(key))
- {
- if (isCover)
- {
- first[key] = second[key];
- }
- }
- else
- {
- first.Add(key, second[key]);
- }
- }
- return first;
- }
- }
- public class Compare<T, TC> : IEqualityComparer<T>
- {
- private Func<T, TC> GetField { get; }
- public Compare(Func<T, TC> getField)
- {
- GetField = getField;
- }
- public bool Equals(T x, T y)
- {
- return EqualityComparer<TC>.Default.Equals(GetField(x), GetField(y));
- }
- public int GetHashCode(T obj)
- {
- return EqualityComparer<TC>.Default.GetHashCode(GetField(obj));
- }
- }
- }
|