Initial Commit
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
TestClassRepo repo = new();
|
||||
|
||||
var test = repo.Get(_ => _.Name == "Test" || _.Id == "TestId2");
|
||||
|
||||
var testexpression = repo.Get(filter: [ new() { Name = "Test2", Description = "Test2" }]);
|
||||
|
||||
Console.WriteLine(test);
|
||||
|
||||
Console.ReadLine();
|
||||
|
||||
public class TestClass
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Id { get; set; }
|
||||
public string Description { get; set; }
|
||||
public bool? IsActive { get; set; }
|
||||
}
|
||||
|
||||
public class TestClassRepo
|
||||
{
|
||||
private List<TestClass> _list = [new() { Name = "Test" , Id = "TestId" }, new() { Name = "Test2" , Id = "TestId2", Description = "Test2" }, new() { Name = "Test3" , Id = "Test3" } ];
|
||||
|
||||
public List<TestClass> Get(Predicate<TestClass>? predicate = null, List<TestClass>? filter = null)
|
||||
{
|
||||
if (predicate != null)
|
||||
{
|
||||
return TestUtils.Get<TestClass>(predicate, _list);
|
||||
}
|
||||
else if (filter != null)
|
||||
{
|
||||
return TestUtils.GetFilter<TestClass>(filter, _list);
|
||||
}
|
||||
|
||||
return _list;
|
||||
}
|
||||
}
|
||||
|
||||
public class TestUtils
|
||||
{
|
||||
public static List<T> Get<T>(Predicate<T> predicate, IEnumerable<T> collection)
|
||||
{
|
||||
List<T> result = [];
|
||||
|
||||
foreach (var item in collection)
|
||||
{
|
||||
if (predicate(item))
|
||||
{
|
||||
result.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<T> GetFilter<T>(List<T> obj, List<T> collection)
|
||||
{
|
||||
ParameterExpression param = Expression.Parameter(typeof(T));
|
||||
Expression predicate = Expression.Constant(true);
|
||||
|
||||
foreach (var item in obj)
|
||||
{
|
||||
PropertyInfo[] properties = typeof(T).GetProperties();
|
||||
|
||||
foreach (PropertyInfo property in properties)
|
||||
{
|
||||
string name = property.Name;
|
||||
var value = property.GetValue(item);
|
||||
|
||||
if (value is not null)
|
||||
{
|
||||
MemberExpression propertyExpression = Expression.Property(param, name);
|
||||
|
||||
ConstantExpression constant = Expression.Constant(value);
|
||||
|
||||
BinaryExpression body = Expression.Equal(propertyExpression, constant);
|
||||
|
||||
predicate = Expression.AndAlso(predicate, body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var lambda = Expression.Lambda<Func<T, bool>>(predicate, param);
|
||||
return collection.Where(lambda.Compile()).ToList();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user