Linq to update a collection with values from another collection?

30,399

Solution 1

To pair elements in the two lists you can use a LINQ join:

var pairs = from d in someData
            join b in baseList.AsEnumerable()
                on d.someCode equals b.myCode
            select new { b, d };

This will give you an enumeration of each item in someData paired with its counterpart in baseList. From there, you can concatenate in a loop:

foreach(var pair in pairs)
    pair.b.SomeData += pair.d.DataIWantToConcantenate;

If you really meant set concatenation rather than +=, take a look at LINQ's Union, Intersect or Except methods.

Solution 2

LINQ is for querying - not for updating. That means it'll be fine to use LINQ to find the corresponding item, but for the modification you should be using iteration.

Admittedly you might want to perform some appropriate query to get baseList into an efficient form first - e.g. a Dictionary<string, SomeClass> based on the property you'll be using to find the corresponding item.

Solution 3

You can convert the IQueryable<SomeClass> into a List<SomeClass>, use the ForEach method to loop over it and update the elements, then convert back to IQueryable:

List<SomeClass> convertedList = baseList.ToList();
convertedList.ForEach(sc =>
{
    SomeOtherClass oc = someData.First(obj => obj.SomeCode == sc.MyCode);
    if (oc != null)
    {
        sc.SomeData += oc.DataIWantToConcatenate;
    }
});

baseList = convertedList.AsQueryable(); // back to IQueryable

But it may be more efficient during this using non-LINQ constructs.

Solution 4

As mentioned before, it should be a combination of loop and LINQ

foreach (var someDataItem in someData)
{
    someDataItem.PropertyToUpdate = (baseList.FirstOrDefault(baseListItem => baseListItem .key == someDataItem.key) ?? new SomeClass(){OtherProperty = "OptionalDefaultValue"}).OtherProperty;
}
Share:
30,399
Hcabnettek
Author by

Hcabnettek

@kettenbach

Updated on July 09, 2022

Comments

  • Hcabnettek
    Hcabnettek almost 2 years

    I have IQueryable<someClass> baseList

    and List<someOtherClass> someData

    What I want to do is update attributes in some items in baseList.

    For every item in someData, I want to find the corresponding item in baselist and update a property of the item.

    someOtherClass.someCode == baseList.myCode

    can I do some type of join with Linq and set baseList.someData += someOtherClass.DataIWantToConcantenate.

    I could probably do this by iteration, but is there a fancy Linq way I can do this in just a couple lines of code?

    Thanks for any tips, ~ck in San Diego

  • stevenrcfox
    stevenrcfox over 12 years
    would it work to do a cross between this approach and the accepted approach, e.g. (from d in someData join b in baseList.AsEnumerable() on d.someCode equals b.myCode select new { b, d }).ToList.ForEach(a=> { a.b.SomeData+=a.d.DataIWantToConcatenate; });