Reputation: 143
In my Xamarin app, there is a Picker which gets the Bank List from Database, and this DB gets the Bank details through an API.
Everything works fine, but now, I want to update the DB, if the new Banks are added in API, I want to add them in the existing database.
I wrote this small code, but the problem is, it first output all the existing records from the database and then print the new records, many times as the total amount of records e.g. (if there are ten records, it will print every record ten times).
ViewModel.cs
// Load all Banks into a List
var getBanks = await App.Database.GetBankAsync();
// Update the Bank Details where new Banks doesn't exist in the Database
List<Bank> updateBanks = new List<Bank>();
foreach (Banks i in obj.banks)
{
foreach (var record in getBanks.Where(c => c.Name != i.alias.name))
{
updateBanks.Add(new Bank { Name = i.alias.name, Status = "Not Registered" });
}
}
foreach (var bank in updateBanks)
{
await App.Database.SaveBankAsync(bank);
}
// Load all Banks into a List
var getBanksUpdated = await App.Database.GetBankAsync();
// Load the Banks whose Status is "Not Registered"
foreach (var record in getBanks.Where(c => c.Status == "Not Registered")
{
_bankList.Add(record);
}
public class Alias
{
public string name { get; set; }
}
public class Banks
{
public Alias alias { get; set; }
public string id { get; set; }
}
public class RootObject
{
public List<Banks> banks { get; set; }
}
Data getting through API
{
success: true,
banks: [
{
alias: {
name: "Bank 1",
Address: "Earth"
},
endpoint: {
uri: "http://127.0.0.1:0000"
},
state: "Registered",
createdAtUtc: "2021-01-19T13:55:12.2318662",
updatedAtUtc: "2021-01-19T13:55:14.9944042"
},
]
}
Code to get the data from API
HttpClient httpClient = new HttpClient(new NativeMessageHandler());
Uri getDataBanks = new Uri(string.Format("http://127.0.0.1:0000/Banks"));
HttpResponseMessage restponseBanks = await httpClient.GetAsync(getDataBanks);
string contentBanks = await restponseBanks.Content.ReadAsStringAsync();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(contentBanks);
Upvotes: 0
Views: 213
Reputation: 1545
// get the names of all existing banks
List<string> names= obj.banks.Select(u => u.Name).ToList();
// get the names of all banks taken from the API
List<string> names_new= getBanks.Select(u => u.Name).ToList();
foreach (var record in names_new)
{
//check if the bank is exists or not
if(! names.contains(record)
{
updateBanks.Add(new Bank { Name = record.alias.name, Status = "Not Registered" });
}
}
Upvotes: 3
Reputation: 570
I'm not aware of your data, but you you have too foreach loops and you are checking the whole collection in every loop. SO, it's possible, that your condition catches every account on every loop.
Upvotes: 1