Search code examples
c#asp.net-mvcjquery-ajaxq

How to add new item into IEnumerable<model> list without deleting the items


[HttpPost]
    public JsonResult AjaxMethod(string[] departments)
    {
        IEnumerable<Batch> batchList = Enumerable.Empty<Batch>();
        try
        {
            string a;
            for (int i = 0; i < departments.Length; i++)
            {
                a = departments[i];
                batchList = batchList.Concat(obj.Batches.Where(x => x.Department_Id == a));
            }
            return Json(batchList);
        }
        catch
        {
            return Json(null);
        }
    }

I am sending AjaxMethod() an array with two indexes departments[0]="BSCS" and departments[1]="BSIT"

And i am using concat method to append IEnumerable list when when for loop runs the 2nd time, it overwrites the result of departments[0] and it concatinates departments[1] with departments[1]

I want this output:

bscs-f13
bscs-f14
bscs-f15
bsit-f13
bsit-f14
bsit-f15

But the actual output is:

bsit-f13
bsit-f14
bsit-f15
bsit-f13
bsit-f14
bsit-f15


Solution

  • Linq functions are pure so concatenation allocates each loop new memory. You can simply iterate the departments argument.

    batchList = departments.SelectMany(d=>obj.Batches.Where(x => x.Department_Id == d));