Home > Back-end >  More efficient ways for foreach loop to add database Items to results List?
More efficient ways for foreach loop to add database Items to results List?

Time:10-02

Is there a more efficient way to add the foundItems to the resultList (for example with more efficient LINQ query / more efficient foreach loop)?

            // 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);
            }

CodePudding user response:

You can use Join for such task:

var resultList = localSysList1
    .Join(databaseList, x => x.Id, x => x.Id, (l, d) => d)
    .ToList();

CodePudding user response:

I could try this

var localSysListIds = localSysList1.Select(i=> i.Id).ToArray();
var resultList = databaseList.Where(x => localSysListIds.Contains(x.Id)).Distinct();

result

    1   Spinach TXT_FLD_SPINA   Some additional info

or maybe this, it makes more sense to me

var resultList = databaseList.Where(x => !localSysListIds.Contains(x.Id)).Distinct();
   
localSysList1.AddRange(resultList);

result

    1   Spinach TXT_FLD_SPINA   something1
    2   Broccoli    TXT_FLD_BRO something else5
    3   Wheatgrass  TXT_FLD_WHE something else4
    4   Banana  TXT_FLD_BANA    something else
    5   Tomatoes    TXT_FLD_TOM something else2
  • Related