【问题标题】:More efficient ways for foreach loop to add database Items to results List?foreach 循环将数据库项添加到结果列表的更有效方法?
【发布时间】:2021-11-23 12:06:59
【问题描述】:

有没有更有效的方法将 foundItems 添加到 resultList(例如更有效的 LINQ 查询/更有效的 foreach 循环)?

            // Ex: Local List
            var localSysList1 = new List<SomeType1>()
            {
                new SomeType1 { Id = "1", Name = "Spinach", Value = "TXT_FLD_SPINA", ExtraInfo = "something1" },
                new SomeType1 { Id = "2", Name = "Broccoli", Value = "TXT_FLD_BRO", ExtraInfo = "something else5" },
                new SomeType1 { Id = "3", Name = "Wheatgrass", Value = "TXT_FLD_WHE", ExtraInfo = "something else4" },
            };

            // Ex: Retrieved from DbContext
            var databaseList = new List<SomeType1>()
            {
                new SomeType1 { Id = "1", Name = "Spinach", Value = "TXT_FLD_SPINA", ExtraInfo = "Some additional info" },
                new SomeType1 { Id = "4", Name = "Banana", Value = "TXT_FLD_BANA", ExtraInfo = "something else" },
                new SomeType1 { Id = "5", Name = "Tomatoes", Value = "TXT_FLD_TOM", ExtraInfo = "something else2" },
            };

            List<SomeType1> resultList = new List<SomeType1>();
            foreach (var localItem in localSysList1)
            {
                var foundItems = databaseList.Where(x => x.Id == localItem.Id);
                resultList.Add(foundItems);
            }

【问题讨论】:

  • 为什么要在 ID 匹配的地方添加项目?通常你会更新那些。您将添加 Id 不匹配的那些(即,尚未在数据库中)。
  • 听起来像是基于属性的 LINQ 相交 - this 应该会有所帮助。
  • LINQ 通常用于第一个代码的快速方法而不是效率。从未见过 ORM 会胜过具有固定计划或批量插入/更新的存储过程。
  • 异端:正确,我写了一些示例代码,它实际上应该与 Value 匹配。
  • Andre:当类型不匹配但属性之一(Id)匹配时,是否也可以使用 Intersect?

标签: c# linq entity-framework-core


【解决方案1】:

编写你自己的相等比较器。

这将比.Where 调用循环中的每个对象快得多。由于您有一个本地列表,看来 ORM 优化并不是您真正想要的。

这应该可行。

Main.cs

...
var eqComparer = new SomeType1EqualityComparer();
var resultList = localSysList1.Intersect(databaseList, eqComparer).ToList();

SomeType1EqualityComparer.cs

public class SomeType1EqualityComparer : IEqualityComparer<SomeType1>
    {
        public bool Equals(SomeType1 x, SomeType1 y)
        {
            if (ReferenceEquals(x, y))
                return true;

            if (ReferenceEquals(x, null))
                return false;
            
            if (ReferenceEquals(y, null))
                return false;

            if (x.GetType() != y.GetType())
                return false;
            
            return x.Id == y.Id && x.Name == y.Name && x.Value == y.Value && x.ExtraInfo == y.ExtraInfo;
        }

        public int GetHashCode(SomeType1 obj)
        {
            return HashCode.Combine(obj.Id, obj.Name, obj.Value, obj.ExtraInfo);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多