I have a List: zephyrPatientDataList with a much simplified model:
public class zephyrPatientDataList
{
public List<zephyrPatientData> patients { get; set; }
}
public class zephyrPatientData
{
public int CustomerID { get; set; }
public int ClaimID { get; set; }
public string ChemistID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<zDispenseScriptData> scripts{get;set;}
}
public class zDispenseScriptData
{
public bool claimItem { get; set; }
public string id { get; set; }
}
This is a list bound to a datagrid. The list shows a Patient and then scripts (prescription medication) that the patient has listed.
From these I have a checkbox for each script (bound to [claimItem] (bool))
I'm getting the user to check the scripts for each patient.
After this I need to upload the scripts to my API.
I have 2 options:
- upload all scripts (could be 200-300) scripts over maybe 10-20 patients.
OR
- create a list of patients and scripts which are marked as
claimItem = TRUE
I have tried to create a copy of the current list (patientList => uploadPatientList)
Then I tried iterating through the uploadPatientList and removing all scripts which were claimItem = FALSE.
foreach (var newPatient in newList.patients)
{
if(newPatient.scripts != null){
for (int i = newPatient.scripts.Count - 1; i >= 0; --i)
{
if (!newPatient.scripts[i].claimItem)
{
newPatient.scripts.Remove(newPatient.scripts[i]);
}
}
}
}
The issue with this (as I found out) is that since they are based on the same memory object, my original list is thus changed. The issue here is that the data shown to the patient now changes to only show checked items.
How do I "clone" a list and then remove items OR create a list but only with the
myList.patients.scripts which have claimItem = true?
CodePudding user response:
Add a list to zephyrPatientData that is just the claimed scripts
public class zephyrPatientData
{
public int CustomerID { get; set; }
public int ClaimID { get; set; }
public string ChemistID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
private List<zDispenseScriptData> _scripts
public List<zDispenseScriptData> scripts
{
get => _scripts
set
{
_scripts = value;
claimedScripts = value.Where(s => s.claimItem).ToList();
}
}
public List<zDispenseScriptData> claimedScripts { get; private set; }
}
With an MVVM approach you also could let the view models maintain the claimed list for you by noting when claimItem changes to true and adding themselves to a list of claimed scripts.
CodePudding user response:
Use System.Linq : if new List data just for read, it's ok because , "ToList()" will new a List.
List<zDispenseScriptData> NewList = YourList.Where(p=>p.claimItem == true).ToList();
and maybe you just make a struct instead of class , it's copy by value naturally like this:
public struct zephyrPatientData { //.... }