Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection.Remove - Cannot convert lambda expression to type because its not a delegate type [closed]

Tags:

c#

c#-4.0

I stumbled across this very strange compiler behavior. I am trying to remove items from ObservableCollection based on some condition. Here is what I have in my code which throws error

public ObservableCollection<StandardContact> StandardContacts { get; set; }
....
StandardContacts.Remove(s => s.IsMarked); //Compiler Error

The error is as follows

Error Cannot convert lambda expression to type 'RelayAnalysis_Domain.Entity.StandardContact' because it is not a delegate type  

Surprisingly, the code below in the same method works

var deleteCount = StandardContacts.Where(s => s.IsMarked).Count(); //This Works

I already have following imports in my class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Entity;

This question may turnout to be silly, but it has had my head scratching.

Note: Even the Intellisence shows the same error

like image 546
Jatin Avatar asked Nov 08 '25 03:11

Jatin


1 Answers

The remove method of Observable collection takes an input of type T (in this case StandardContract), not a Func<T, bool>. You may consider writing your own extension method for ICollection if this functionality will be useful to you:

public static void RemoveWhere<T>(this ICollection<T> collection, Func<T, bool> predicate)     {
var i = collection.Count;
while(--i > 0) {
    var element = collection.ElementAt(i);
    if (predicate(element)) {
        collection.Remove(element);
    }
}

Which would the be useable like so:

StandardContacts.RemoveWhere(s => s.IsMarked)
like image 90
Rich O'Kelly Avatar answered Nov 10 '25 20:11

Rich O'Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!