Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: How to insert data while looping through multiple lists

I am attempting to insert data from two List. I am able to successfully insert from one List but adding the second list using a foreach loop does not work as expected.

How do I loop through each of these list so that I can insert their values?

Code:

    private void InsertList()
    {
        var listA = new List<string>();
        var listB = new List<string>();

        //Populate both list by splitting items in listbox

        foreach (ListItem item in ListBox1.Items)
        {
            var components = item.Value.Split('/');

            listA.Add(components.First());

            listB.Add(components.Last());
        }

        using (DataContext dataContext = new DataContext())
        {
            foreach (var itemA in listA)
            {
                foreach (var itemB in listB)
                {

                    LIST_OBJECTS listObject = new LIST_OBJECTS
                    {
                        LIST_ITEM_A = itemA,
                        LIST_ITEM_B = itemB
                    };

                    dataContext.LIST_OBJECTS.Add(listObject);

                }

            }

            dataContext.SaveChanges();
        }
    }
like image 936
Asynchronous Avatar asked May 31 '26 11:05

Asynchronous


2 Answers

What about a for loop?

for (var i = 0; i < listA.Count; i++) 
{ 
    LIST_OBJECTS listObject = new LIST_OBJECTS
    {
        LIST_ITEM_A = listA[i], 
        LIST_ITEM_B = listB[i]
    }; 
    dataContext.LIST_OBJECTS.Add(listObject);
}

Since you know from the creation of the Lists that they'll have the same number of elements, this is fine.

like image 103
jdphenix Avatar answered Jun 03 '26 00:06

jdphenix


You can do it with LINQ

LIST_OBJECTS listObject = listA.Join(listB,
                                     a=>listA.Indexof(a),
                                     b=>listB.Indexof(b),
                                     (a,b)=> new LIST_OBJECTS()
                              {
                                   LIST_ITEM_A =a,
                                   LIST_ITEM_B =b 
                               }).ToList();
like image 21
Hossein Salmanian Avatar answered Jun 03 '26 01:06

Hossein Salmanian