Search code examples
c#listlistobject

I want to create multiple objects in list<object> and remove them with the desired id


I want to delete it with the desired id.

Can you tell me if there is another way to do it with Linq?

I think I can use Select() and Where(), but it doesn't work.

var list = new List<object>() { };
list.Add(new { id = 3, const = "22"});
list.Add(new { id = 4, const = "22"});
list.Add(new { id = 6, const = "22"});
list.Add(new { id = 2, const = "22"});
list.Add(new { id = 1, const = "22"});

//example
list.Remove(new { id = 2, const = "22" });

Solution

  • first of all const is a keyword in C#, so either avoid using it as member name, or escape it by decorating with @.

    since your list item type is object, you need to cast them as dynamic to allow access the 'unknown' id -> this a very vague approach, but it works. = in C# means: set the value of... so if you want to compare equality, you need ==

    putting this altogether:

      var list = new List<object>();
      list.Add(new { id = 4, @const = "22" });
      list.Add(new { id = 4, @const = "22" });
      list.Add(new { id = 6, @const = "22" });
      list.Add(new { id = 2, @const = "22" });
      list.Add(new { id = 1, @const = "22" });
    
      list.RemoveAll(i => ((dynamic)i).id == 2);
    

    will work.

    Consider using an own Type for your list items, anonymous types should only be used 'locally' in Queries like GroupBy.