I have a struct like this:
public struct stuff
{
public int ID;
public int quan;
}
and want to to remove the product where ID
is 1.
I'm trying this currently:
prods.Remove(new stuff{ prodID = 1});
and it's not working.
THANKS TO ALL
This question is related to
c#
.net
entity-framework
linq
If your collection type is a List<stuff>
, then the best approach is probably the following:
prods.RemoveAll(s => s.ID == 1)
This only does one pass (iteration) over the list, so should be more efficient than other methods.
If your type is more generically an ICollection<T>
, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where
or Single
).
prods.Remove(prods.Single(p=>p.ID == 1));
you can't modify collection in foreach, as Vincent suggests
Here is a solution for those, who want to remove it from the database with Entity Framework:
prods.RemoveWhere(s => s.ID == 1);
And the extension method itself:
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace LivaNova.NGPDM.Client.Services.Data.Extensions
{
public static class DbSetExtensions
{
public static void RemoveWhere<TEntity>(this DbSet<TEntity> entities, Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var records = entities
.Where(predicate)
.ToList();
if (records.Count > 0)
entities.RemoveRange(records);
}
}
}
P.S. This simulates the method RemoveAll()
that's not available for DB sets of the entity framework.
You can only remove something you have a reference to. So you will have to search the entire list:
stuff r;
foreach(stuff s in prods) {
if(s.ID == 1) {
r = s;
break;
}
}
prods.Remove(r);
or
for(int i = 0; i < prods.Length; i++) {
if(prods[i].ID == 1) {
prods.RemoveAt(i);
break;
}
}
prods.Remove(prods.Find(x => x.ID == 1));
You could use Linq.
var prod = from p in prods
where p.ID != 1
select p;
If you have LINQ:
var itemtoremove = prods.Where(item => item.ID == 1).First();
prods.Remove(itemtoremove)
Source: Stackoverflow.com