Linq spit numeric list in search (kentico) - c#

In kentico the standard way to get documents in below (which I believe is based on ObjectQuery and has linq commands). Im trying to filter it by one more field "newsCategory" which contains data like "1|2|3". So I cant add .Search("newsCategory", 1) etc because I need to split the list before I can search it. What direction should I be looking? A select sub-query? (Im new to linq)
// Get documents
var news = DocumentHelper.GetDocuments("CMS.News")
.OnSite("CorporateSite")
.Path("/News", PathTypeEnum.Children)
.Culture("en-us")
.CombineWithDefaultCulture(false);

As far as this is a field from the coupled table, you can't access it through property, but have to use GetValue() instead. Once you've got, you can work with it like with regular string:
var news = DocumentHelper.GetDocuments("CMS.News")
.OnSite("CorporateSite")
.Path("/News", PathTypeEnum.Children)
.Culture("en-us")
.CombineWithDefaultCulture(false)
.Where(d => d.GetStringValue("newsCategory","").Split('|').Contains("1"));

Are you sure your data is 1|2|3 and not 1|2|3| or |1|2|3 ?
If it is, you could do .Where("NewsCategory", QueryOperator.Like, "%" + id + "|%")
Otherwise you may have to get back more results, and then loop through them and split the values to find the exact one you want.

EDIT: Check out this article that shows some more advanced where commands you can use with the Data Query API. You should be able to MacGyver a proper filter with those options.
I believe you're looking for:
.WhereLike("DocumentCategoryID", "CategoryID");
//OR
.WhereLike("DocumentCategory","CategoryName");
I don't have v8 installed to double check which exact key/value pair to filter by, but according to this Document Query API article you filter document sets with the WhereLike() method.
According to the API documentation, GetDocuments() returns a MultiDocumentQuery object. I'm not 100% certain if that implements IEnumerable, so you may not even be able to use LINQ with it.

I believe something like this would work. There is a wherein property that should be able to pull the value out. Not exactly sure how it would handle the scenario of having a 1 and then an 11, but it may be work looking into.
// Get documents
var news = DocumentHelper.GetDocuments("CMS.News")
.OnSite("CorporateSite")
.Path("/News", PathTypeEnum.Children)
.Culture("en-us")
.CombineWithDefaultCulture(false)
.WhereIn("NewsCategory",1);

Related

Return Values That Are In Lowercase

We recently discovered a bug in our system whereby any serial numbers that have been entered in lowercase have not been processed correctly.
To correct this, we need to add a one off function that will run through the database and re-process all items with lower case serial numbers.
In linq, is there a query I can run that will return a list of such items?
Note: I am not asking how to convert lowercase to uppercase or reverse, which is all google will return. I need to generate a list of all database entries where the serial number has been entered in lowercase.
EDIT: I am using Linq to MS SQL, which appears to be case insensitive.
Yes, there is. You can try something like this:
var result = serialnumber.Any(c => char.IsLower(c));
[EDIT]
Well, in case of Linq to Entities...
As is stated here: Regex in Linq (EntityFramework), String processing in database, there's few ways to workaround it.
Change database table structure. E.g. create table Foo_Filter which will link your entities to filters. And then create table Filters
which will contain filters data.
Execute query in memory and use Linq to Objects. This option will be slow, because you have to fetch all data from database to memory
Note: link to MSDN documentation has been added by me.
For example:
var result = context.Serials.ToList().Where(sn => sn.Any(c => char.IsLower(c)));
Another way is to use SqlMethods.Like Method
Finally, i'd strongly recommend to read this: Case sensitive search using Entity Framework and Custom Annotation

LINQ pull records from a database where string list is from a model

I have a database of strings that contain IDs. I need to pass that list into a LINQ query so I can pull the correct records.
model.SelectedDealers = db.dealers.Any(a => a.sdealer_name.Contains(UserToEdit.UserViewAccesses.Select(s => s.ViewReferenceNumber)));
SelectedDealers is of type dealers
ViewReferenceNumber should be a list of strings which should match sdealer_name
So essentially I am trying to find all of the dealers whos sdealer_name matches the list of sdealer_names I have in my UserToEdit.UserViewAccesses
I've tried moving parts around and switching them in different spots and can't seem to figure this out.
Any() is just a boolean indicating if there are any results. It doesn't actually return the results.
If I understand what you are after correctly, then this might work:
var dealerNames = UserToEdit.UserViewAccesses.Select(s => s.ViewReferenceNumber).ToList();
model.SelectedDealers = db.dealers.Where(a => dealerNames.Contains(a.sdealer_name));
So essentially I am trying to find all of the dealers whos
sdealer_name matches the list of sdealer_names I have in my
UserToEdit.UserViewAccesses
var dealersthatmatched = (from d in UserToEdit.UserViewAccesses.sdealer_names
where d == sdealer_name
select d).ToList()
Wish I could have made a comment instead, but as I don't have enough rep I can't. I wish I understood the requirement better, but you seem ready and able to try stuff so perhaps you find this useful.

asp.net searching for a string

I have some data coming in from a webpage and I need to filter it based on what comes back.
I have a pre-defined amount of keywords that I want to search for, around 30.
What is the most efficient way to match them up? Because I can have ~2000 records coming in I don't think searching through a list/array/switch-case for every record is too efficient right?
Besides list/array/switch-case, the only thing I can think of is Linq.
List<string> found = (from str in listOfStringsToSearch
where listOfKeywords.Any(keyword => str.Contains(keyword))
select str).ToList<string>();
If you just want to know which serach terms have matching strings, you can use Enumerable.Intersect:
var both = records.Intersect(searchTerms);
It is deferred executed, hence does not create a new collection and is not executed until you use it in some way(f.e. ToList or foreach or string.Join).
It internally uses a Set, hence it is very efficient.
Here are more informations on set operations in LINQ:
http://msdn.microsoft.com/en-us/library/bb546153.aspx

Dynamically adding select fields using LINQ lambda

Lets say we have an expression:
var prices = from p in PriceDB.Prices
where p.TypeID == 12
orderby p.PriceType.Title
select p;
Is it possible to modify the select list?
I imagine it looking something like this:
var newPriceList = prices.Select( p => p.ExchangeRate );
This may be an odd request, but in my code (which is too long and complex to post here) I want to conditionally add fields to be output depending on a CheckBoxList.
I assume, of course, that I'm trying to go about this the wrong way...
I imagine it looking something like this:
Actually it would look exactly like that. First, build a query, selecting the entire record. Then add a select (using the Select() method seem the easiest way) to limit the selection. Linq-to-Sql will sort out the two selects, and use the proper reselt, so theres just one select in the final SQL.
There's no really good way to choose between multiple selects. I would probably use a switch/case.
While you could go down the dynamic route, I would strongly consider not doing so. What is the cost of fetching the extra values if you don't need them, in your particular case? Is the problem that they're being displayed dynamically and you only want them displayed in certain cases? If so, I'd suggest modifying the display code somehow.
It's hard to stay strongly typed (which has various advantages) while being dynamic in terms of what you fetch. Of course, if you always want to fetch the same "shape" of data (e.g. always just a decimal value from each row) then that's reasonably easy - let me know if that's something you'd like to see demonstrated.
If you could tell us more about your problem, we may be able to suggest alternative solutions.
If I understood you correct this is explaining how to build dynamic queries:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
You might want to look at this Dynamic LINQ and Dynamic Lambda expressions?
Or the Dynamic Expression API (System.Linq.Dynamic).

How to get a distinct list of first letters with NHibernate

I have been landed into the middle of a project that is using MVC2 & NHibernate. I haven't worked with NHibernate before, so as simple as this question might seem, I'm a bit out of my depth.
I have to create a directory for a number of Company Groups. The first task is to get a distinct list of the first letter for each company.
So if we have
ACompany1
ACompnay2
BCompany1
DCompany1
DCompany2
ECompany1
I need to get a list like
A B D E (note, there's no 'C')
Can somebody please provide me with an outline of what I need to do? Thanks
Assuming the class name is Company and the property is Name...
var groups = session.CreateQuery(
"select distinct substring(Name, 1, 1) from Company")
.List<string>()
I wonder if you are approaching this from the wrong direction. NHibernate is used to map your database objects to your domain objects. You could create some custom map file that use a formula to get you the distinct characters but I think this is one of those cases where a simple SQL query would suffice.
The alternative would be load all the companies into Memory and use linq to get the names.
companies.Select(company => company.Name.Substring(0, 1));
I sometimes get blinkered when using a mocking framework and struggle to mock a particular entity, it isn't till I step back I realise that it would be easier and cleaner to mock my own entity.
First you need to decide how will you do it with sql. Probably you will use some kind of SUBSTRING function. After you solve it, you can write similar HQL query.

Categories