Linq Crosses Arrays

Im getting table tags from db.

table has column identifiers and tag

I am doing something like this to get a list of strings:

var taglist = Model.Tags.Select(x => x.TagName.ToLower()).ToArray(); 

then I compare with another string array to get the strings that are found in both:

 var intersectList = tagList.Intersect(anotherList); 

I have a list, but now I also want the identifier of each element to remain in the intersection list that matches the tagList. (maybe just an int array)

Can someone help with a good way to do this?

+4
source share
3 answers

Do not use intersect, it only works for collections of the same type. You can do a simple join or some other form of filtering. It would be easiest to list the list of strings in a HashSet and filter out the tags containing the TagName in this set. This way you keep your tags undesigned so that they retain their identifiers and other properties.

 var stringSet = new HashSet<string>(anotherList); var tagList = Model.Tags.Where(t => stringSet.Contains(t.TagName)).ToList(); 

And put them on the list. Do not throw them into an array unless you need a specific array (for use in a method that expects an array).

+6
source

Perhaps use Dictionary<int, string> instead of Array ?

0
source

Could you do:

 var intersectIds = Model.Tags .Where(tag => anotherList.Contains(tag.TagName)) .Select(tag => tag.Id) .ToList(); 
0
source

Source: https://habr.com/ru/post/1392352/


All Articles