-2
[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

faraz
  • 63
  • 11
  • You are building up a list of objects, not reading an existing list. So use a `List` and `Add()` instead of `IEnumerable` and `Concat()` – Rhumborl Jul 16 '17 at 08:56
  • i tried it but then it shows the error that cannot convert from iqueryable to batch – faraz Jul 16 '17 at 08:58

1 Answers1

2

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));
Cihan Yakar
  • 2,402
  • 28
  • 30