This question already has answers here:
Linq Select All Items Matching Array
(2 answers)
Linq filter List<string> where it contains a string value from another List<string>
(4 answers)
Closed 4 years ago.
How can I create LINQ expression to find elements from collection contains names from string array?
string[] names = ["John", "Hanna", "Bill", "Donald"];
I've created expression like below but it is not correct. How can I fix that?
result = (x => x.CompanyEmployeeName.Contains(names));
If you want check if names contains x.CompanyEmployeeName, you'll want to use:
result = something.Where(x => names.Contains(x.CompanyEmployeeName));
let myCollection be the collection of a custom class having a property Name. you have to get all objects from that collection based on the condition that object's name should be available in the names array. Then You can try this:
var filteredItems = myCollection.Where(x=> names.Any(y=>y == x.Name));
I have added a working example here
In your LINQ, you should have a collection first.
Ex: if you have a list: listCompanyEmployee then you can use bellow expression:
var result = listCompanyEmployee.Where(x => names.Contains(x.CompanyEmployeeName));
You need to reverse it. Check if the names contains the employee
var result = db.CompanyEmployee.Where(x => names.Contains(x.CompanyEmployeeName));
One other option, which is prefered if the list in context are larger then your sample data, is to use Join
var result = db.CompanyEmployee.Join(names, x=> x.CompanyEmployeeName, n => n, (x,n)=> n);
You can use Array.Exists. Example if you want to check if names contains CompanyEmployeeName:
result = something.Where(x => Array.Exists(names, name => name == x.CompanyEmployeeName));
and you can use Array.IndexOf like:
result = something.Where(x => Array.IndexOf(names, x.CompanyEmployeeName) != -1);
Related
This question already has answers here:
LINQ Contains Case Insensitive
(11 answers)
Closed 3 months ago.
I have the following code
query = query.Where(x => words.Any(x.Message.Contains));
words is a string[] and x.Message is a string
I would like to filter out my query based on all the words in my array but I would like this not to be case sensitive comparison so if i type 'bob' or 'BOb' it should not care and still compare those words against the message if Message is 'BOB is awesome' or 'bob is awesome'
A better option is to use Contains overload with StringComparison parameter:
query = query.Where(x => words.Any(s => x.Message
.Contains(s, StringComparison.InvariantCultureIgnoreCase)));
This will compare the list of strings to the message as you desire. I use .ToLower() to convert both the string and each word in the list so it's essentially case-insensitive.
query = query.Where(x => words.Any(s => x.Message.ToLower().Contains(s.ToLower())));
Check if a string contains an element from a list (of strings): Check if a string contains an element from a list (of strings)
I have a string like this:
RoleId,RoleName|CategoryId,CategoryName
I split them first like this:
string delm = "RoleId,RoleName|CategoryId,CategoryName";
string[] FieldsToReplace = attributes[0].IdsToReplaceWith.Split('|');
Suppose i have a variable in which i have RoleId:
string test = "RoleId";
Now what i am trying to get each the array item in which has string RoleId, i don't want to use contains i need exact match.
I have tried this query:
var test = FieldsToReplace
.Where(x=>FieldsToReplace
.All(y => y.Split(',').Equals(delm))).ToArray();
i can harcode like this for first index:
var IdProperty = FieldsToReplace.FirstOrDefault(x => x.Split(',')[0] == delm);
but i want it dynamic so it check each item of array which i got after , split.
but it returns no record.
Any help will be appreciated.
You want to split on your elements of the array. Besides that it seems appropriate to check if any element of these splitted ones are equal to your comparison string:
var test =
FieldsToReplace
.Where(x => x.Split(',')
.Any(y => y.Equals(prop.Name)))
.ToArray();
This question already has answers here:
Compare the difference between two list<string>
(3 answers)
Closed 8 years ago.
I am trying to find values of string which aren't includes into other list.
I have list like:
var list1 = new List<string>();
list1.Add("element1");
list1.Add("element2");
var list2 = new List<string>();
list2.Add("element1");
list2.Add("element2");
list2.Add("element3");
I need to find elements from list2 which aren't in list1, so the result should be only:element3. I tried to do something like right join with LINQ, but it was unsuccessful. Maybe someone know proper solution for this?
Use Enumerable.Except
Produces the set difference of two sequences by using the default
equality comparer to compare values.
var result = list2.Except(list1);
Another way of doing that could be:
var result = list2.Where(r => !list1.Contains(r));
If you need a List<string> as result, then just add ToList().
list1.Except(list2)
Returns the set difference between 2 IEnumerables: MSDN
Use Except
var list3 = list2.Except(list1);
list2.Except(List1)
.Except() should work
This question already has answers here:
How can I find a specific element in a List<T>?
(8 answers)
Closed 6 years ago.
I have a list containing the following structure.
class CompareDesignGroup
{
string FieldId;
string Caption;
}
The list is containing items of the above structure.
Is it possible to retrieve an element of the list if FieldId is known?
You can use the Find method on the generic list class. The find method takes a predicate that lets you filter/search the list for a single item.
List<CompareDesignGroup> list = // ..;
CompareDesignGroup item = list.Find(c => c.FieldId == "SomeFieldId");
item will be null if there is no matching item in the list.
If you need to find more than one item you can use the FindAll method:
List<CompareDesignGroup> list = // ..;
List<CompareDesignGroup> result= list.FindAll(c => c.FieldId == "SomeFieldId");
You can use LINQ like this:
CompareDesignGroup result = yourList.FirstOrDefault(x => x.FieldId == yourKnownId);
If you use the FirstOrDefault method the result will be null when list doesn't contain a record with a known id. So before using result check if it is not null.
There are a plethora of methods to find an item inside a list.
LINQ provides extensions method useful to work with collections that does not provide their own search features (or when you do not have the collection itself but a generic interface like IEnumerable<T>). If you have a List<CompareDesignGroup> object and you'll work on that object you can use the methods provided by that class (specialized methods are almost always faster than LINQ methods, they know collection's internal structure and does not have to rely on many abstraction layers).
In all examples I'll perform a culture invariant and case sensitive comparison for FieldId to a hypothetical id parameter. This may not be what you need and you may have to change according to your requirements.
Using List<T>
Given a list declared as:
List<CompareDesignGroup>() list = new List<CompareDesignGroup>();
To find first element that matches the search criteria (it'll return null if no items have been found):
CompareDesignGroup item = list.Find(
x => String.Equals(x.FieldId, id, StringComparison.InvariantCulture));
To find all the elements that matches the search criteria:
List<CompareDesignGroup> items = list.FindAll(
x => String.Equals(x.FieldId, id, StringComparison.InvariantCulture));
Using IEnumerable<T> (or IList<T>, for example)
Given a list declared as:
IEnumerable<CompareDesignGroup> list = ...
To find first element that matches the search criteria (null if no items have been found):
CompareDesignGroup item = list.FirstOrDefault(
x => String.Equals(x.FieldId, id, StringComparison.InvariantCulture));
To find the first element that matches the search criteria (or throw an exception if no items have been found):
CompareDesignGroup item = list.First(
x => String.Equals(x.FieldId, id, StringComparison.InvariantCulture));
To find all elements that matches the search criteria:
IEnumerable<CompareDesignGroup> item = list.Where(
x => String.Equals(x.FieldId, id, StringComparison.InvariantCulture));
There are many LINQ extensions methods, I suggest to take a look to them all to find the one that better suits your needs.
You can use Where and then you can use FirstOrDefault. That is an LINQ expression.
var ls = new List<CompareDesignGroup>();
var result = ls.Where(a => a.FieldId=="123").FirstOrDefault();
Or SingleOrDefault to get the item you want. Like this:
var ls = new List<CompareDesignGroup>();
var result = ls.Where(a => a.FieldId=="123").SingleOrDefault()
Or even simpler:
var result = ls.SingleOrDefault(a => a.FieldId=="123");
var result2 = ls.FirstOrDefault(a => a.FieldId=="123");
Yes. Use LINQ or the built-in functionalities of List.
List<CompareDesignGroup> listData = new List<CompareDesignGroup>(); // init the data
var result = listData.Where(x=> String.Equals(x.FieldID,"FIELDID KNOWN VALUE"); // gets all data
var first = listData.FirstOrDefault(x=> String.Equals(x.FieldID,"FIELDID KNOWN VALUE"); // gets first search result
Im getting a table Tags from the db.
the table has columns ID and TagName
I'm doing something like this to get a list of strings:
var taglist = Model.Tags.Select(x => x.TagName.ToLower()).ToArray();
then I'm comparing against another string array to get the strings that occur in both:
var intersectList = tagList.Intersect(anotherList);
I have my list, but now I also want the ID of each item remaining in the intersect list that corresponds to the tagList. (can just be an int array)
Can anyone help with a good way to do this?
Don't use intersect, it only works for collections of the same type. You could do a simple join or other form of filtering. It would be easiest to throw the string list into a HashSet and filter by tags that contain TagNames in that set. This way, you keep your tags unprojected so they keep their ids and other properties.
var stringSet = anotherList.ToHashSet(StringComparer.OrdinalIgnoreCase);
var tagList = Model.Tags.Where(t => stringSet.Contains(t.TagName)).ToList();
And put them into a list. Don't throw them into an array unless you specifically need an array (for use in a method that expects an array).
Could you do:
var intersectIds = Model.Tags
.Where(tag => anotherList.Contains(tag.TagName))
.Select(tag => tag.Id)
.ToList();
Maybe use Dictionary<int, string> instead of Array?