How to use Out to pass multiple values from list in C#

422 views Asked by At

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?

1

There are 1 answers

0
ispiro On

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.