Condition in generic lists - list

I'm wondering is there any condition instead of T-SQL like in generic lists in C# 4.0.
I've got a gridview on my page I got all datas and I need to search by name and lastname, so I think there must be but I couldn't find yet.

Use String.Contains, String.StartsWith or String.EndsWith as part of a predicate, either using List<T>.FindAll or Where in LINQ.
For example:
var jons = people
.Where(p => p.FirstName.StartsWith("Jon", StringComparison.CurrentCultureIgnoreCase))
.ToList();

Thats called Contains

Related

I can't directly cast object in my Entity Framework query using ValueInjecter

I'm trying to use ValueInjecter to map my entities to my DTOs in my asp.net core project.
Could someone explain me why this works:
var list = _context.Assets
.ToList();
var vm = list
.Select(a => new ViewModel().InjectFrom(a))
.Cast<ViewModel>()
.ToList();
return vm;
But this doesn't:
var list = _context.Assets
.Select(a => new ViewModel().InjectFrom(a))
.Cast<ViewModel>()
.ToList();
return list;
Is this a ValueInjecter bug? Am I doing something wrong?
Would Automapper solve this? I strongly prefer valueinjecter syntax compared to Automapper.
Thanks for your help!
Edit:
#Chris Pratt: Thanks for your quick answer. But why would it work when I map properties manually like the example below. I'm still applying this mapping to the IQueryable interface not in-memory.
Then why this works?
var vm = _context.Assets
.Select(a => new ViewModel
{
Id = a.Id,
Code = a.Code
})
.AsNoTracking()
.ToList();
return vm;
I haven't used ValueInjector, but my guess is that it comes down to the Select being applied in-memory in the first example and to the query in the second example. Dynamic mapping is not something that can be done at the database level, and specifically, EF must be able to translate the things you pass in Select, Where, etc. into SQL. It will not be able to do so with the ValueInjector code, and hence cannot construct a query to satisfy the LINQ expression. You do not have this issue in the first example, because you pull then entities from the database first, and then you map those in-memory instances.
For what it's worth, AutoMapper would have the same problem here, so it's not technically a mapping provider problem - just one of where the operation is going to be run (i.e. in-memory vs. at the database).

Rails 4: the right way to initialize hash table from database?

my first question, be gentle :-)
I have a rails application using pieces of text from a database (table basically contains a short key k and the corresponding text; sort of like i18n, but for reasons out of scope here I don't want to use that right now). Made a small helper function for the views to get the matching text by key, along the lines of "Text.find_by k: x". Hell of a database load but allowing the texts to be changed dynamically by a CMS.
But since it turned out that the texts do rarely change, I wanted to preload the whole table into a hash instead. Since I'm not sure where to put such initialization stuff, and also because I thought lazy loading might be cool, here is what I did (simplified):
module MainHelper
...
##items = nil
def getText(x)
initItems if !##items
##items[x]
end
private
def initItems
##items = {}
Text.all.each {|t| ##items[t.k] = t.text} #load from model
end
Which seems to work great. But since I am quite a newbie here, I wonder if anybody thinks there is a better solution, or a solution that is more "the rails way"? Any comments highly appreciated!
What you've done is pretty cool. I'd be more likely to make a method items that memoizes the items, as opposed to an explicit initItems method. That would be the more conventional solution.
Use pluck to get only the fields in the table that you need... it'll make the SQL call more efficient.
because pluck in this case returns an array of two-element arrays, it's easy to use the to_h method to convert it into a hash.
(also, convention is to use snake_case for method names)
module MainHelper
...
##items = nil
def get_text(x)
items[x]
end
private
def items
##items ||= Text.pluck(:k,:text).to_h #load from model
end
end

How to perform search for multiple terms in Sitecore 7 ContentSearch API?

I am exploring the new Sitecore.ContentSearch "LINQ to Sitecore" API in Sitecore 7. It is my understanding that Sitecore recommends using the new LINQ API over the existing Sitecore.Search API, however, I am struggling to perform even the simplest of queries.
Take for instance the following search query: "hello world".
Using the Sitecore.Search API, the terms "hello world" would typically be passed through a QueryParser which would result in documents matching the word "hello" OR "world". Documents containing both terms would be scored higher that those with just one.
How does one perform this same query using LINQ?
Here's what I have tried:
var results = SearchContext.GetQueryable<MyResultItem>();
var terms = searchTerm.Split(' ');
// Not supported exception
results = results.Where(r => terms.Any(t => r.Content.Contains(r)));
// Close, but performs an "AND" between terms, and does not appear
// to score documents properly
foreach (var term in terms)
{
results = results.Where(r => r.Content.Contains(t));
}
UPDATE
I am convinced that I am missing something really simple. Surely with all the work that went into the new search API, this simple use case wasn't overlooked... right?
As a workaround, I tried opening the default sitecore_web_index using the existing SearchManager, however, this does not work.
Unfortunately, I have had to resort to the existing API until I can figure this out. I will be sure to update this question with my findings.
UPDATE 2
I found the Sitecore.ContentSearch.Utilities.LinqHelper class which partially solves the problem. You can use it to dynamically build a query similar to a BooleanQuery in Lucene.Net, however, it's options are limited and it adds a bit of performance overhead.
All of the predicate builders I tried didn't work, however, Sitecore 7 ships with a PredicateBuilder of it's own that did the trick.
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.ContentSearch.Utilities;
// Sitecore 7 (Update 1+): using Sitecore.ContentSearch.Linq.Utilities;
...
var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var predicate = PredicateBuilder.True<SearchResultItem>();
foreach (var t in term.Split(' '))
{
var tempTerm = t;
predicate = predicate.Or(p => p.Content.Contains(tempTerm));
}
var results = context.GetQueryable<SearchResultItem>().Where(predicate).GetResults();
...
}
I think this is related to linq not to sitecore.
I don't test this but have a look at this article http://www.albahari.com/nutshell/predicatebuilder.aspx
You can also look at this documentation http://sdn.sitecore.net/upload/sitecore7/70/developer's_guide_to_item_buckets_and%20search_sc7-a4.pdf
I was able to use PredicateBuilder with Solr and implement queries including the OR operator. See http://www.nttdatasitecore.com/en/Blog/2013/November/Building-Facet-Queries-with-PredicateBuilder.aspx

OpenCart Wishlist

I'm trying to parse out the wishlist column in open cart's wishlist_to_store column to retrieve the product ID's. At first glance I thought it was being stored as JSON, but that obviously not the case. Is there a library or method I can use to parse it out?
Example wishlist:
a:2:{i:0;s:5:"16419";i:1;s:5:"16415";}
The method you are looking to use is called unserialize(). This is fairly similar in function to what JSON does but is the PHP equivalent. You can use it as follows
$a = unserialize('a:2:{i:0;s:5:"16419";i:1;s:5:"16415";}');
var_dump($a);

Methods for filtering within a Doctrine results Collection?

I'm very new to Doctrine, so this might seem a rather obvious question to those more experienced.
I'm writing a data import tool that has to check every row being imported contains valid data. For example, the Row has a reference to a product code, I need to check that there is a pre-existing Product object with that code. If not, flag that row as invalid.
Now I can easily do something like this for each row.
$productCode = $this->csv->getProductNumber();
$product = $doctrine->getRepository('MyBundle:Product')->findOneBy(array('code' => $productCode ));
But that seems hideously inefficient. So I thought about returning the entire Product Collection and then iterating within that.
$query = $this->getEntityManager()->createQuery('SELECT p FROM MyBundle\Entity\Product p');
$products = $query->getResult();
All well and good, but then I've got to write messy loops to search for.
Two questions:
1). I was wondering if I'm missing some utility methods such as you have in Magento Collections, where you can search within the Collection results without incurring additional database hits. For example, in Magento this will iterate the collection and filter on the code property.
$collection->getItemByColumnValue("code","FZTY444");
2). At the moment I'm using the query below which returns an "rectangular array". More efficient, but could be better.
$query = $this->getEntityManager()->createQuery('SELECT p.code FROM MyBundle\Entity\Product p');
$products = $query->getResult();
Is there a way of returning a single dimensional array without have to reiterate the resultset and transform into a flat array, so I can use in_array() on the results?
If I understand your question correctly you want to filter an array of entities returned by getResult(). I had a similar question and I think I've figured out two ways to do it.
Method 1: Arrays
Use the array_filter method on your $products variable. Yes, this amounts to a "loop" in the background, but I think this is a generally acceptable way of filtering arrays rather than writing it yourself. You need to provide a callback (anonymous function in 5.3 preferred). Here is an example
$codes = array_filter($products, function($i) {
return $i->getCode() == '1234';
});
Basically in your function, return true if you want the result returned into $codes and false otherwise (not sure if the false is necssary, or if a void return value is sufficient).
Method 2: Doctrine's ArrayCollection
In your custom repository or where ever you are returning the getResult() method, you can instead return an ArrayCollection. This is found in the Doctrine namespace Doctrine\Common\Collections\. More documenation on the interface behind this method can be found here. So in this case you would have
$query = $this->getEntityManager()->createQuery('SELECT p FROM MyBundle\Entity\Product p');
$products = new ArrayCollection($query->getResult());
You can then use the filter() method on the array collection. Use it in a very similar way to the array_filter. Except it doesn't need a first argument because you call it like this: $products->filter(function($i) { ... });
The ArrayCollection class is an iterator, so you can use it in foreach loops to your hearts content, and it shouldn't really be different from an array of your products. Unless your code explicitly uses $products[$x], then it should be plug 'n' play*.
*Note: I haven't actually tested this code or concept, but based on everything I've read it seems legit. I'll update my answer if it turns out I'm wrong.
You can use another hydration mode. $query->getResult() usually returns a result in object hydration. Take a look at $query->getScalarResult(), which should be more suitable for your needs.
More info on the Doctrine 2 website.