This should be quite easy, however I am failing to see why all my methods are not working.
I have looked at all the solutions and used them appropriately however am not getting the result.
solutions include
Here is the code:
IEnumerable<feature> available = _repo.GetAvailableFeatures();
IEnumerable<feature> selected = _repo.GetSelectedFeatures();
Using Except
var filteredList = (available.Except(selected)).ToList;
Using Linq
var availableList = available.ToList();
var selectedList = selected.ToList();
availableList.RemoveAll(item => selectedList.Contains(item));
Using old fashion for
for (var i = 0; i < availableList.Count - 1; i++)
{
foreach (var t in selectedList)
{
if (availableList[i].Id == t.Id)
{
availableList.RemoveAt(i);
}
}
}
My Feature class looks like this:
public class Feature
{
public int Id;
public int Desc;
}
Can anyone see it my mistakes here?
When you use Except
you need to define what "equal" means for the feature
type, otherwise reference equality (are they the same object) is used by default. In your loop you define "equal" as " Id
s are equal", so some options are:
Equals
and GetHashCode
in the feature
class
IEqualityComparer<feature>
Use Where
instead of Except
:
var filteredList = available.Where(a => !selected.Any(s => s.Id == a.Id)) .ToList();
This looks like a straightforward process of comparing the two data lists to each other and removing them in a standard fashion. I would personally go with a List setup instead of IEnumerable.
List<Feature> availableList = _repo.GetAvailableFeatures();
List<Feature> selectedList = _repo.GetSelectedFeatures();
foreach(Feature avail in availableList){
if(selectedList.Contains(avail)){
selectedList.Remove(avail)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.