Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to update a collection with values from another collection?

Tags:

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

like image 318
Hcabnettek Avatar asked Jul 21 '09 18:07

Hcabnettek


People also ask

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

What is meant by LINQ in C#?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

Which LINQ API is used to connect and work with collections?

LINQ and strings (C#) LINQ can query and transform strings and collections of strings. You can combine LINQ queries with C# string functions and regular expressions.


2 Answers

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.

like image 41
Jon Skeet Avatar answered Oct 27 '22 11:10

Jon Skeet


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.

like image 153
dahlbyk Avatar answered Oct 27 '22 11:10

dahlbyk