my issue is that I have an attribute as ‘attribute’ coming in from entity framework.
So I retrieve this object which has a list of attribute tags, they are accessible via attribute.AttributeTags. Now I have a asp:TextBox where users can edit, remove and add new tags (comma separated). (On page load I am adding the attribute tags to this TextBox)
After a postback on the page I am returning the user input and splitting it into an array of strings and storing it in a variable called AttributeTags.
Now, I would like to add new tags that are not contained in the original attributes list coming from EF and would like to remove the ones that are contained in attributes but not found in the user input string array AttributeTags.
I am doing something like this:
BusinessObjects.Attribute attribute = db.Attributes.FirstOrDefault(a => a.attribute_id == AttributeID);
string[] AttributeTags = txtAttributeTags.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in AttributeTags)
{
if (!attribute.AttributeTags.Any(t => t.value == item))
{
AttributeTag tag = new AttributeTag { value = item, timestamp = DateTime.Now };
attribute.AttributeTags.Add(tag);
}
else
{
AttributeTag tag = attribute.AttributeTags.FirstOrDefault(t => t.value == item);
}
}
But I’m sort of stuck here since i’m fairly new to LINQ and EF.
I have two solution of this situations.
First Solution
We can create an
ExcepWithmethod that will allow us to remove all the items in aICollection<T>that are already in give aIEnumerable<T>. The code for such method follows:Now you have an
string[]with the input of the user, that array is anIEnumerable<string>but not an anICollection<string>… that is easily solved as follows:Instead of this:
You do this:
Or even this:
Now you can do this:
Since the type of attribute.AttributeTag is not
IEnumerable<string>you use Select:And that leaves only the new tags in the list.
Note: this method depends on the implementation of Remove, if you need to do an special comparison, then you are out of luck with this method.
Second Solution
There is another way. You can use the Except from the
Enumerableclass.Since the type of attribute.AttributeTag is not
IEnumerable<string>you use Select:And that puts in newTags, well, the new tags.
Note: If you need to do an special comparison, then you should use the other overload of the method:
Sadly the equalityComparer is an object of a class that implements IEqualityComparer, meaning that you can’t use lambdas there. For that you can add this class:
And now invoke like this (for example):
Since the type of attribute.AttributeTag is not
IEnumerable<string>you use Select:Adding the new tags
Now that you have the new tags, let’s say in
newTags, you can iterate it to add the new tags:Comparing the Solutions
What’s the difference of these methods?
IEqualityComparer<T>