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
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
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.
A bit late to the game, however, a simple extension method can implement a RemoveAll on IList<T>. The trick is to loop over the collection in reverse order to avoid the extra logic of deleting the current item and having to try on the current index if removed. Also the reverse order prevents having to copy all the remaining items. Depending on the .NET version, this copy could be expensive.
public static int RemoveAll<T>(this IList<T> list, Predicate<T> match)
{
if (list == null) throw new ArgumentNullException("list");
if (match == null) throw new ArgumentNullException("match");
int count = 0;
for (int i = list.Count - 1; i >= 0; i--)
{
if (match(list[i]))
{
++count;
list.RemoveAt(i);
}
}
return count;
}