一般使用LINQ查找项属性值相等的所有项

lhcgjxsq  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(122)

我正在尝试实现一个通用仓库模式,该模式实现了IEnumerable中通用项的CRUD操作。我遇到了一个问题,即通用地查找可能已经在IEnumerable中的项。
我需要以编程方式传递哪些属性组成了“键”或不同的记录,然后使用LINQ对定义的属性执行Enumerable.Any(),这样它就可以查看对象是否已经存在于IEnumerable中。
下面是我目前的代码:

// Generic Method
    public void AddItem(TEntity item)
    {
        var entities = GetAllItems().ToList(); // Method gets cached IEnumerable<TEntity>
        
        if(true)  // Generically see if TEntity is already in the list based of defined properties
        {
            entities.Add(item);
        }

    }

    // Same function but non-generic
    private void AddItem(MyObject object)
    {
        var objects = GetAllItems().ToList(); //Method gets cached IEnumerable<MyObject>
        
        if(!objects.Any(a=> a.ID == MyObject.ID ))
        {
            objects.Add(object);
            _cache.AddReplaceCache(objects);
        }
    }

注意:键可以是对象MyObject上的任何属性

xxhby3vn

xxhby3vn1#

You can make your entities inherit from a common interface:

public interface IEntity
{
    int ID { get; set; }
}

Then you can redefine your method like

public void AddItem<TEntity>(TEntity entity) where TEntity : IEntity
{
    // Now you can access entity.ID
}

Now, if you don't always want to compare via ID, then you can add a predicate to your method:

public void AddItem<TEntity>(TEntity entity, Func<TEntity, bool> predicate)
{
    var objects = GetAllItems().ToList();

    // You might need some logic in the predicate to check for null
    if(!objects.Any(a => predicate(a as TEntity))
    {
        objects.Add(entity);
        _cache.AddReplaceCache(objects);
    }

}

Then you would use your function as

repository.AddItem(entity, e => e.ID == entity.ID && e.OtherProperty == entity.OtherProperty);
wwodge7n

wwodge7n2#

如果我没理解错的话,你的问题是TEntity没有属性ID。所以让你的实体继承公共接口,比如ID列。

public interface IObject
{
    int ID {get; set;}

    //define all other properties which are shared between your Entities.
}
public class MyObject : IObject
{
    public int ID {get; set;}

    //other properties.
}

public void AddItem(TEntity item): where TEntity:IObject
{
    var entities = GetAllItems().ToList(); //Method gets cached IEnumerable<TEntity>

    if(!objects.Any(a=> a.ID == item.ID ))//Generically see if TEntity is already in the list based of defined properties
    {
        entities.Add(item);
    }

}

相关问题