Uladz Kha
Uladz Kha

Reputation: 2354

How to delete all Items from List by parentId

I have a Simple CRUD application with categories and phones, For single delete phone from List i uses:

var arrayPhones = new List<Phone>();
        using (StreamReader file = new StreamReader(@"d:/phones.json"))
        {
            var strPhones = file.ReadToEnd();
            arrayPhones = JsonConvert.DeserializeObject<List<Phone>>(strPhones);


            var currentPhone = arrayPhones.Where(p => p.Id == phone.Id).SingleOrDefault();
            arrayPhones.Remove(currentPhone);
        }

Now i tring delete Category and all Phones of this category, model of my Phone:

 public class Phone
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("parentId")]
    public int ParentId { get; set; }

    [JsonProperty("caption")]
    public string Caption { get; set; }

    [JsonProperty("imgUrl")]
    public string ImgUrl { get; set; }

How i can delete all phones of category? Thanks for answers!

Upvotes: 0

Views: 52

Answers (3)

Jack B
Jack B

Reputation: 391

Seems some info is missing. How is your Category class defined? How does your Phone class reference the Category?

Say if Phone has a prop CategoryId, it would be something like:

var phonesOfThisCategory = arrayPhones.Where(p => p.CategoryId == category.Id);

foreach(var aPhone in phonesOfThisCategory)
{
    arrayPhones.Remove(aPhone);
}

Upvotes: 2

M.S.
M.S.

Reputation: 4413

For multiple records, select which are not to be removed and assign to list,

arrayPhones = arrayPhones.Where(p => p.Id != phone.Id).ToList();

Upvotes: 1

user2216
user2216

Reputation: 839

Try to use this RemoveAll method

Upvotes: 1

Related Questions