create method with two list itterate on booth and add to another list in csharp

Here's an example method that takes two lists as input, iterates over them simultaneously, and adds their elements to a new list:

main.cs
public List<int> AddLists(List<int> list1, List<int> list2)
{
    List<int> result = new List<int>();
    int minLength = Math.Min(list1.Count, list2.Count);

    for (int i = 0; i < minLength; i++)
    {
        result.Add(list1[i] + list2[i]);
    }

    return result;
}
274 chars
13 lines

The AddLists method starts by creating a new empty list called result. It then determines the minimum length of the two input lists using Math.Min(list1.Count, list2.Count). This is necessary to ensure that we don't get an "out of range" exception when iterating over the lists.

Next, we use a for loop to iterate over both lists simultaneously. The loop runs for minLength iterations, since we only want to add up the corresponding elements in list1 and list2.

Inside the loop, we use the Add method to add the sum of the current elements in list1 and list2 to the result list.

Finally, we return the result list containing the sum of the corresponding elements from both input lists.

gistlibby LogSnag