Reputation: 432
I have a list of objects as such:
someID: 1234 values: A, B
someID: 891 values: C
I have a datatable with some rows.
1234 D
891 E
1234 F
I want to add these values from the datatable
to their respective objects in the list in-memory. So for example, I want to find the object with ID
1234 in the list and add values D
and F
to the object.
What would have the best performance?
Edit: not really a DB question, I'll try to make it more clear
Upvotes: 0
Views: 162
Reputation: 11
You just need to iterate through the rows, search up the id and add the value to it
foreach (DataRow item in datatable.Rows)
{
<YourType> thing = list.Find(x => x.someID == (int)item[0]);
if (thing == null)
{
List<string> values = new List<string>();
values.Add(item[1].ToString());
list.Add(new <YourType> { someID = (int)item[0], values = values });
}
else
{
thing.values.Add(item[1].ToString());
}
}
Upvotes: 1
Reputation: 460238
You can use Linq-To-DataSet
:
var both = from row in dt.AsEnumerable()
join objA in objectAList
on row.Field<int>(0) equals objA.someID
select new { row, objA };
foreach(var x in both)
{
x.objA.values.Add(x.row.Field<string>(1)); // presuming an `IList<T>`
}
If it's not a list but for example an array, you can use:
x.objA.values = x.objA.values.Concat(new[]{x.row.Field<string>(1)}).ToArray();
Enumerable.Join
uses a set under the hood so it's rather efficient.
Upvotes: 1
Reputation: 5260
For what you need, create primary key on the ID and do upinsert (update or insert is not exist) - so you will need to performa 1 operation for each ID and can create store procedure that append the new data.
From your question seem that you want to do bulk operation - meaning doing all those operation in memory and than update the database in 1 operation. For that you use hash table
Upvotes: 0