Linq Filter Array of Delimited Strings - c#

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();

Related

LINQ filter string with value string

I have a string str = "abc,def,ghi". The length of string will vary. There could be one or more values separated by comma.
I have an object that has a property Code that is string and can contain values such as - "abc, stu, xyz"
I'm trying to filter objects from a collection that will return only those that contain a string in str
So, if object.Code = "abc, stu, xyz" and string str = "abc,def,ghi" then return the object.
objects.Where( x => x.Code.Split(',').Any(s => (???)) );
where ??? is where my string str values will come in.
Thanks,
var result = objects.Where(x => x.Code.Split(',').Any(s => (str.Split(',').Any(f => f.Equals(s)))));
Conversion of the str to a HashSet will improve the testing speed and simplify the query, but perhaps is overkill if your objects only have a few entries. I assume the Code property does not have spaces after each comma.
var strHash = str.Split(',').ToHashSet();
var ans = objects.Where(o => o.Code.Split(',', StringSplitOptions.RemoveEmptyEntries).Any(c1 => strHash.Contains(c1)));

Find String matches any in List of Strings

How to find string with a exact match in the list of string.
var inv_attr_string_id = inv_attr
.Where(x => ItemStringVal.Contains(x.STRING_VAL))
.Select(x => x.ID).ToList();
ItemStringVal Contains list of Strings like "0030", "1433", "2019" etc ... Now I am trying to match it with the database in such a way that if it match exactly and all the three strings then it returns me the list of IDs matched ... else it should return null.
I tried
List<int> inv_attr_string_id = new List<int>();
foreach (var StrItem in ItemStringVal)
{
inv_attr_string_id.AddRange
(
inv_attr.Where(x => x.STRING_VAL.Contains(StrItem))
.Select(x => x.ID).ToList()
);
}
I have tried .Any as well but I got an error saying "Internal .NET Framework Data Provider error 1025"
I was thinking if I could be able to write it the way it creates a query of AND condition such as it should match (Exactly) all the input strings.
One Liner could be: Select IDs if all the string matches. Else return null
If I understand the problem - You have a list of strings which is your Input Data. You also have a List of patterns that may match with Data. You want to find the pairs of [Data, Pattern]?
Upfront this can be solved in O(N^2).
Psuedo Logic be like:
Foreach item in DataCollection
Foreach pattern in PatternCollection
if(Regex.IsMatch(item, pattern)) Then collect the item & pattern in some place
Hope this gives some starting point for you to solve the problem.
You can try linq to get all those records from db which are exist int your list
var result = inv_attr.AsEnumerable().Where(x => ItemStringVal.Exists(y => y == x.STRING_VAL)).Select(x => x.Id).ToList();

Find elements from collection contains names from string array [duplicate]

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);

Compare if elements in string array exists in another list c#

I have an string array and a list of string. For example,
string[] stringArray = {"car", "bike", "truck"};
List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};
From the array and list, I want to compare stringArray with stringList and retrieve items that are in the stringArray and is also part of the stringList.
Eg: the items retrieved should be, 'car_blue', 'car_red' and 'truck_yellow'?
You could use LINQ' Where to filter the stringList using the parts before the _:
var result = stringList.Where(x => stringArray.Contains(x.Split('_')[0]));
You have to Split by _ to get all tokens, then you can use Intersect...Any:
var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_')).Any());
If you want to ignore the case, so also accept Car_Yellow:
var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_'), StringComparer.OrdinalIgnoreCase).Any());
The Best way where you don't have to use split is
string[] oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToArray();
or if you want list
List<string> oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToList();

C# lambda Expression In where clause

I’m having issues creating an Where clause using C# and lambdas.
I have the following method GetRecommendedstudents(Guid studId)
The variable string filtersByRoles can hold a comma-delimited value such as: "xp,windows,windows8 or "xp,windows,windows8,windo " etc..
I then have the following C# lambda query:
I need get data from database by comparing 2 fields.
enter code here
var student= DataContext.students.Find(studId);
ex: var x = DataContext.students.Where(L => (L.job == student.studentJobLocation)).AsQueryable();
Next i want comapare student know os("xp,windows,windows8 )
ex: var y = x.students.Where(L => (s => (s.jobOperaitngsys.Split(',') == student.studentknowOS)), StringSplitOptions.RemoveEmptyEntries);
How to compare this to fields? jobOperaitngsys and studentknowOS
you should use contain. because split returns string array.
s.jobOperaitngsys.Split(',').Contains(student.studentknowOS)

Categories

Resources