0

I have created 2 separate lists using the page model like this:

@model IEnumerable<Batch>
@{
    ViewBag.Title = "Batches";
    bool FirstEveningBatch = true;
    List<Batch> WeekDaysBatch = new List<Batch>(Model.ToList());
    List<Batch> WeekEndBatch = new List<Batch>(Model.ToList());
}

Now I'm calling the extension method using the first list as in the below

@foreach (var item in WeekDaysBatch.Where(x => !x.IsWeekendBatch).AppendBatchNumber())
{
    // ... some code ...
}

Here is the AppendBatchNumber() extension method:

public static IEnumerable<Batch> AppendBatchNumber(this IEnumerable<Batch> batches)
{
    bool IsFirstEveningBatch = true;
    int batchnumber = 0;

    Batch[] batchesArray = batches.OrderBy(x=> x.StartTime).ToArray();

    for (int i = 0; i < batchesArray.Length; i++)
    {
        if (batchesArray[i].Name.StartsWith("Evening") && IsFirstEveningBatch)
        {
            batchnumber = 0;
            IsFirstEveningBatch = false;
        }

        batchesArray[i].Name = string.Format("{0}-{1}", batchesArray[i].Name, ++batchnumber);
    }

    return batchesArray;
}

But the second list WeekEndBatch is also getting altered. Is there any way how we can avoid the alteration of the second list?

Here is the Batch class:

public class Batch
{
    public int Id { get; set; }
    public string Name { get; set; }

    [NoBatchAfter9PM]
    public TimeSpan StartTime { get; set; }

    [NoBatchAfter9PM]
    public TimeSpan EndTime { get; set; }

    public string? Description { get; set; }

    [Display(Name="Is it a Weekend batch?")]
    public bool IsWeekendBatch { get; set; }

    [Display(Name = "Is it a Women's batch?")]
    public bool IsWomenBatch { get; set; }

    public ICollection<Learner>? Learners { get; set; }
    public Coach? Coach { get; set; }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sagar Tube
  • 59
  • 5

1 Answers1

1

The reason why both lists are getting updated is that the Model object you're calling back is referenced and isn't actually a copy. You will want to create a clone of it like is mentioned here - Using Clone() to duplicate an ASP.NET MVC / EntityFramework model object

Then what will happen is that you have copies of the object not the actual object itself. I don't know if this will help in your case if you want to modify the original object but if thats the case, just use Model.ToList in WeekDaysBatch and then use the clone in WeekEndBatch for any transient work you want to do.

Melroy Coelho
  • 212
  • 2
  • 6