I need to compare the exact string values with the database.
e.g. string vals = "bicycle_store,clothing_store"
in the database i have other values containing word "store" e.g. electronics_store
when I execute the below linq it finds all contains "store" word. How can I update the linq so it only sets "selected = true" to what is been sent
return (from x in _ctx.Category
select new CategoryVM
{
Text = x.Text,
Value = x.Value,
Selected = vals.Contains(x.Value) == true ? true : false
}).ToList();
You should split the values first:
string vals = "bicycle_store,clothing_store";
string[] values = vals.Split(',');
return (from x in _ctx.Category
select new CategoryVM
{
Text = x.Text,
Value = x.Value,
Selected = values.Contains(x.Value)
}).ToList();
This will translate into a SQL IN statement.
Use where:
return (from x in _ctx.Category
where vals.Contains(x.Value)
select new CategoryVM
{
Text = x.Text,
Value = x.Value
}).ToList();
If you want to limit the output to the given input(s) exactly, do not use a single string. String.Contains will return true if a given value is within the string at all, so "bicycle_store".Contains("store") will return true, since the word "store" exists within the word "bicycle_store".
Instead, use a string array. A Contains on an array will only return true if the string matches one of the elements exactly.
string[] valsArray = vals.Split(',');
return (from x in _ctx.Category
where valsArray.Contains(x.Value)
select new CategoryVM
{
Text = x.Text,
Value = x.Value
}).ToList();
Related
The query
select * from PositionTable where Position in (51000785,52012986)
returns two records where the position column is '51000785' in the first record and '52012986' in the second.
Using C# I want to return the same results..I have tried
string allPositions = "51000785,52012986";
List<PositionTable> Position = new List<PositionTable>();
Position = DbContext.PositionTableList
.Where<PositionTable>(p => p.Position == allPositions)
.ToList();
This result returns nothing, so how can I change the ==allPositions to 'in (allPositions)' is this possible?
Thanks
Try something like this:-
var allPositions = new string[] { "51000785", "52012986" };
var x = from p in DbContext.PositionTableList
where allPositions.Contains(p.Position)
select p;
FilePrefixList.Any(s => FileName.StartsWith(s))
Can I get s value here? I want to display the matched string.
Any determines only if there is a match, it doesn't return anything apart from the bool and it needs to execute the query.
You can use Where or First/FirstOrDefault:
string firstMastch = FilePrefixList.FirstOrDefault(s => FileName.StartsWith(s)); // null if no match
var allMatches = FilePrefixList.Where(s => FileName.StartsWith(s));
string firstMastch = allMatches.FirstOrDefault(); // null if no match
So Any is fine if all you need to know is if ther's a match, otherwise you can use FirstOrDefault to get the first match or null(in case of reference types).
Since Any needs to execute the query this is less efficient:
string firstMatch = null;
if(FilePrefixList.Any(s => FileName.StartsWith(s)))
{
// second execution
firstMatch = FilePrefixList.First(s => FileName.StartsWith(s));
}
If you want to put all matches into a separate collection like a List<string>:
List<string> matchList = allMatches.ToList(); // or ToArray()
If you want to output all matches you can use String.Join:
string matchingFiles = String.Join(",", allMatches);
Not with Any, no... that's only meant to determine whether there are any matches, which is why it returns bool. However, you can use FirstOrDefault with a predicate instead:
var match = FilePrefixList.FirstOrDefault(s => FileName.StartsWith(s));
if (match != null)
{
// Display the match
}
else
{
// Nothing matched
}
If you want to find all the matches, use Where instead.
if FilePrefixList is a List<string>, you can use List<T>.Find method:
string first = FilePrefixList.Find(s => FileName.StartsWith(s));
fiddle: List.Find vs LINQ (Find is faster)
List<T>.Find (MSDN) returns the first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T
Enumerable.Any() returns bool denoting whether any item matched the criteria.
If you need the matched item, use SingleOrDefault() instead:
var matchedPrefix = FilePrefixList.SingleOrDefault(s => FileName.StartsWith(s));
See MSDN
please check try this:
we assuming FilePrefixList is collectionlist
class A
{
public int ID { get; set; }
public string Name { get; set; }
}
List<A> FilePrefixList= new List<A>();
FilePrefixList.Add(new A
{
ID = 1,
Name = "One"
});
FilePrefixList.Add(new A
{
ID =2,
Name = "Two"
});
FilePrefixList.Add(new A
{
ID = 3,
Name = "Three"
});
select data from list is:
var listItems = FilePrefixList.Where(x =>x.Name.StartsWith("T")).ToList();
I am trying get the data which is contains single word with in the word.Like below query.
List<Models.tbluser> memberslist = new List<Models.tbluser>();
var obct = (from memlist in objcontext.tblusers
where memlist.logname.Contains(member)
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();
foreach (var item in obct)
{
memberslist.Add(new tbluser
{
userid = item.userid,
logname = item.logname,
description = item.decription
});
}
return Json(memberslist);
But here my problem is i need to search with out case sensitive.
For example
If i search with 'a' i need to get data like Admin,Administrator,User Data.
But i am not getting all these because i am searching with Contains() method.Please let me know how can i get all value either the search value is case sensitive less also.
Change your where condition to be:
memlist.logname.ToUpper().Contains(member.ToUpper())
As a side note, you can shorten your query a bit (you don't need to create an intermediary list):
var memberslist = objcontext.tblusers
.Where(x => x.logname.ToUpper().Contains(member.ToUpper())
.AsEnumerable()
.Select(x => new tbluser
{
userid = x.userid,
logname = x.logname,
decription = x.description
})
.ToList();
return Json(memberslist);
You can change them to Lower or Upper Case when checking the condition using ToLower() or ToUpper():
var obct = (from memlist in objcontext.tblusers
where memlist.logname.ToLower().Contains(member.ToLower())
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();
I have code where I try to find QProduct by productName in a List<QProduct> (lqp) usinq LINQ. The variable productNameInaccurate I get from file name and often contains some other text usually at the end of the string. So for example the productName = '0/2' and the productNameInaccurate that I get from fileName is '0/2 new' etc.
I have this code:
//Get inaccurate product name from filename
productNameInaccurate = fileName.Substring(ind + 1, ind2 - ind - 1).Replace("-", "/");
//Get filtered list of products
List<QProduct> filtered = lqp.Where(x=>productNameInaccurate.StartsWith(x.Name, StringComparison.InvariantCultureIgnoreCase)).ToList();
//Some more filtering - here I need to get best match by productName
if (isDop)
qProduct = filtered.Where(x => x.normy.StartsWith("ČSN EN")).FirstOrDefault();
else
qProduct = filtered.Where(x => !x.normy.StartsWith("ČSN EN")).FirstOrDefault();
It works ok, but I have also productName = '32/63' and productName = '32/63 B I'. This code finds QProduct that has productName == '32/63' even if productNameInaccurate == '32/63 BI'.
What I need is to find best match from the list of QProduct, so that for productNameInaccurate='0/2 new' I get QProduct.Name = '0/2' and for productNameInaccurate='32/63 Bi' I get QProduct.Name = '32/63 B II' instead of QProduct.Name = '32/63'. Ideally get the filtered list sorted by count of matching characters.
"Ideally get the filtered list sorted by count of matching characters."
// Get the filtered list and sort by count of matching characters
IEnumerable<QProduct> filtered = lqp
.Where(x=>productNameInaccurate.StartsWith(x.Name, StringComparison.InvariantCultureIgnoreCase))
.OrderByDesc(x => Fitness(x.ProductName, productNameInaccurate));
static int Fitness(string individual, string target) {
return Enumerable.Range(0, Math.Min(individual.Length, target.Length))
.Count(i => individual[i] == target[i]);
}
I'm trying to select the max values of 3 columns from a table. All the fields being returned from the query are Strings.
What I have sofar
var step1 = from result in t_hsbc_staging_trts_derived_tbl_ac_balance.AsQueryable()
where result.branch_no == brnchnu
&& result.deal_id == dealid
&& result.group_mbr == grpmem
&& result.ac_type != "RMC"
select result ;
var branch = from result in step1
select new {ccbranch = result.cc_branch.Max()};
var sect = from result in step1
select new { ccsect = result.cc_sect.Max()};
var dept = from result in step1
select new { ccdept = result.cc_dept.Max()};
foreach (var result in branch)
{
string cc_branch = result.ccbranch.ToString();
}
The error I'm getting at the foreach statement is:
Sequence operators not supported for type 'System.String'.
There must be an easier way to just get the max values from this table?
You are calling the Max() function on result.cc_branch which is itself a string. Even if it was successful, it would return the character of the string that has the largest unicode number, i.e.
string s = "one-two-three";
Console.WriteLine(s.Max()); // returns 'w'
Since I assume that is not what you want, and that you want the largest branch / section / department value, you can use:
string branch = (from result in step1 select result.cc_branch).Max();
string sect = (from result in step1 select result.cc_sect).Max();
string dept = (from result in step1 select result.cc_dept).Max();