1

I have a situation where I'm passing an array of data (it can be any number, not fixed) from front-end, which is received as list in my API. I need each of the record's primary key value in order to pass them in my controller again to do further task. But using out, I am not able to return multiple data, it only returns the final value after finishing the loop.

Code-

public bool Add(List<Model> model) //have tried using out, but not working as I want
{
    Model obj = new Model();
    bool saved = false;
    int id = 0;
    foreach (Model m in model)
    {
        var data = _repo.Get(x => x.Id == m.Id);
        var isExist = _repo.AsQueryable().Count();
        if (isExist <= 0)
        {
            maxId = 1;
        }
        else
        {
            maxId = _repo.AsQueryable().Max(x => x.Id) + 1;
        }
        obj.Id = maxId; //the maxId for each loop iteration needs to be passed as out to fulfill my situation
        obj.Name= m.Name;
        obj.Dept= m.Dept;
        _repo.Add(obj);
        isSaved = true;
    }
    return isSaved;
}

Is there any way to return the maxId after each iteration or all maxId all together to my controller?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
XenDex
  • 23
  • 4
  • 3
    Cant you just add Them all to a List and Then return the list? – Victor Oct 10 '21 at 11:52
  • What are you actually trying to do? What's the point of `var isExist = _repo.AsQueryable().Count();` if you have `var data = _repo.Get(x => x.Id == m.Id);` to check to see if it exists? – Ermiya Eskandary Oct 10 '21 at 11:57
  • While this probably compiles. the logic is an absolute mess - I'd rather you just gave expected input and output – Ermiya Eskandary Oct 10 '21 at 12:01
  • What about returning a tuple? You can have this signature: public (List model, bool isSaved) Add() – Yom B Oct 10 '21 at 12:05

1 Answers1

0

To return all at once create a List and either make that the return type of the method:

public List<TypeYouWantToReturn> Add(...)
{
   List<TypeYouWantToReturn> list = new List<TypeYouWantToReturn>();
   //make a loop and add the results here: list.Add(something);
   return list;
}

or make it an out parameter as you mentioned:

public bool Add(out List<TypeYouWantToReturn> list)
{
   //make a loop and add the results here: list.Add(something);
   return true;
}

or use yield return to return values one by one.

ispiro
  • 26,556
  • 38
  • 136
  • 291