Unity 通过条件筛选数据,过滤相同数据,和差异数据
可以对比任意数据,自定义筛选条件
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
public class Data
{
#region 对比数据
public delegate bool DelCondition<T>(T data1, T data2);
/// <summary>
/// 对比两个数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="datas1">数据1</param>
/// <param name="datas2"></param>
/// <param name="condition">数据2</param>
/// <param name="suffice">筛选条件</param>
/// <param name="datas1Contain">只有data1包含的数据</param>
/// <param name="datas2Contain">只有data2包含的数据</param>
public static void Compare<T>(T[] datas1, T[] datas2, DelCondition<T> condition, out T[] suffice, out T[] datas1Contain, out T[] datas2Contain)
{
List<T> data1List = datas1.ToList();
List<T> data2List = datas2.ToList();
Compare<T>(datas1, datas2, condition, out suffice);
for(int i=0;i< suffice.Length;i++)
{
T temp = suffice[i];
data1List.Remove(temp);
data2List.Remove(temp);
}
datas1Contain = data1List.ToArray();
datas2Contain = data2List.ToArray();
}
/// <summary>
/// 对比两个数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="datas1">数据1</param>
/// <param name="datas2">数据2</param>
/// <param name="condition">筛选条件</param>
/// <param name="suffice">返回满足条件的数据集合</param>
public static void Compare<T>(T[] datas1, T[] datas2, DelCondition<T> condition, out T[] suffice)
{
var temp = from data1 in datas1
from data2 in datas2
where condition(data1, data2)
select data1;
suffice = temp.ToArray();
}
#endregion
}
使用方法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mx.Util;
public class Test : MonoBehaviour
{
private void Awake()
{
int[] datas1 = { 1,2,4,5,7,8};
int[] datas2 = {1,2,3,9,10,11};
int[] res=null;
int[] datas1Contain,datas2Contain;
Data.Compare<int>(datas1, datas2, condition, out res,out datas1Contain,out datas2Contain);
for(int i=0;i<res.Length;i++)
{
Debug.Log("共同的数据:"+res[i]); //结果是1,2
}
for (int i = 0; i < datas1Contain.Length; i++)
{
Debug.Log("datas1独有:" + datas1Contain[i]);//结果是4,5,7,8
}
for (int i = 0; i < datas2Contain.Length; i++)
{
Debug.Log("datas2独有:" + datas2Contain[i]);//结果是3,9,10,11
}
}
private bool condition(int data1,int data2)
{
return data1 == data2;
}
}