w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Using the WHERE clause and not filtering a thing
You would first test if they selected the ALL value before adding the where clause. $sql = " SELECT * FROM tbl"; if($brand != 'ALL'){ $sql .= " WHERE brand = '{$brand}'"; }

Categories : PHP

Filtering a datatable row using a where clause
Select() is returning an array of rows, and you're assigning it to a single row. You can do : DataRow dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).First(); or var dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()); which will give you an array of rows.

Categories : C#

MySQL "LIKE" clause for filtering against strings
If I understand correctly you can do it with a query like this SELECT COUNT(*) matches FROM filter WHERE 'Me.And.My.Dog.At.The.Lake' LIKE CONCAT('%', filter, '%') Note: reverse upload name and filter when doing comparison with LIKE return just the number of rows in the resultset using COUNT() instead of returning a resultset that potentially can contain multiple rows (even if it's only ids) and then read the count on the client side. Consider using prepared statements instead of interpolating query strings. Here is SQLFiddle demo

Categories : PHP

Parsing and constructing filtering queries similiar to SQL WHERE clause in Python/JavaScript
Have a look at https://github.com/dfilatov/jspath It's similar to xpath, so the syntax isn't as familiar as SQL, but it's powerful over hierarchical data.

Categories : Javascript

Simplifying linq when filtering data
var filtered = bigList.GroupBy(c=>c.Id) .Select(g=> { var f = g.First(); f.Count = g.Sum(c=>c.Count); return f; });

Categories : C#

Filtering with Linq to Entity Framework
Something like this should work: var records = from r in _context.Promotions let maxversion = (from v in _context.Promotions where v.PromoID == t.PromoID select v.VersionDate).Max() where r.Type == "Live" && r.VersionDate == maxversion && !_context.Promotions.Any(p => p.PromoID = t.PromoID && p.Type=="Draft") select r

Categories : Linq

Linq filtering in a property's getter
You will need to convert IEnumerable<Worker> to ObservableCollection<Worker>. You can do this by passing your IEnumerable into the constructor of the ObservableCollection when you create a new one as below: return new ObservableCollection<Worker>(DataManager.Data.MasterWorkerList.Where(w => w.Known == true)); You can make your code more readable by defining an extension method . This can be done as: public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException("source"); } return new ObservableCollection<T>(source); } Thusly, your code would become very simple and readable public ObservableCollection<Worker> Workers { get

Categories : C#

'IN ALL' clause in LINQ
If you can modify the ReduceResult class, then you can implement IEquatable and add Equals method and override GetHashCode(). Like this: public class ReduceResult: IEquatable<ReduceResult> { public string Text { get; set; } public string UserName { get; set; } public string ProfileImageUrl { get; set; } public bool Equals(ReduceResult other) { } public override int GetHashCode() { } } You can then compare the two ReduceResult like any other primary types like int, string. eg, ReduceResult1 == ReduceResult2 If not, then you can create a Comparer class: class ReduceResultComparer : IEqualityComparer<ReduceResult> { public bool Equals(ReduceResult x, ReduceResult y) { } public int GetHashCode(ReduceResult reduceresu

Categories : C#

Linq filtering causes property to not update view
While this isn't really "using LINQ filtering", if you're using ObservableCollection you can use a PagedCollectionView to add a filter to the collection. PagedCollectionView items = new PagedCollectionView(Workers); items.Filter = (o) => (o as Worker).Known != true; Then bind to items. The problem with LINQ is that it creates a new collection, and so it breaks bindings. It's still possible to use it, but it can be a bit tiresome. Let me know if the above isn't what you need, and I'll try to figure something else out. ;) EDIT: PagedCollectionView is only available in Silverlight. If you're using WPF, then you can try something like this: ICollectionView items = CollectionViewSource.GetDefaultView(Workers); items.Filter = (o) => (o as Worker).Known

Categories : C#

LINQ to SQL - Filtering the dataset between two nested collections
It sounds like you're looking for something like: var desiredSkillIds = desiredSkills.Select(_=>_.SkillId).ToList(); var matchingContacts = from contact in Contacts where contact.Role == null || desiredRoles.Contains(contact.Role) where contact.Skills.Any(cs=> desiredSkillIds.Contains(cs.SkillId)) select contact; Or in method-based syntax: var matchingContacts = Contacts .Where(contact => contact.Role == null || desiredRoles.Contains(contactRole)) .Where(contact => contact.Skills.Any(cs => desiredSkillIds.Contains(cs.SkillId)));

Categories : Asp Net Mvc

Strongly typed Linq filtering method
Have you tried simple || conditions? return _db.Entities .Where(x => id == null || x.Id == id.Value) .Where(x => startDate == null || x.StartDate >= startDate.Value) .Where(x => endDate == null || x.EndDate <= endDate.Value) .Where(x => statusId == null || x => x.EntityStatus.StatusID == statusId); ? I would expect that after query optimization, the no-op filters would be equivalent to not adding the filters at all.

Categories : C#

LINQ filtering based on preview filter
Yes, you can do this. Declare your variable at the top using the IQueryable type that would be used by the different sections, and then selectively apply the filter based on your logic. Dim query = InitializeQuery() ' returns type IQueryable(Of YourCustomClass) If cbo1.SelectedIndex > -1 Then 'LINQ filter query = from x in query where x.Condition1 = cbo1.SelectedValue select x End If If me.cbo2SelectedIndex > -1 Then 'Filtering the LINQ again with data from the first combobox... query = from x in query where x.Condition2 = cbo2SelectedIndex.SelectedValue select x End If The type of query stays the same throughout. The only thing that changes in each branch is its definition.

Categories : Dotnet

Dynamic linq enums filtering error
I think the problem is that the dynamic linq library you are using does not support any Enum methods, such as Enum.Equals(otherVal), or Enum.ToString(). One way to get around this, if you have to use dynamic-linq is : public IList<Student> FindByType(StudentType type) { return _students.AsQueryable().Where("Type = (@0)", type).ToList(); } However, if you are able to use standard linq, and you really want to pass in a string for some reason, something like this is much cleaner: public IList<Student> FindByType(string type) { return _students.Where(s => s.Type.ToString().StartsWith(type)).ToList(); } Edit : If you need the ability to search using StartsWith and you are not allowed to use the standard linq query above, here is something that will give the same re

Categories : C#

Dynamic where clause in LINQ?
Where awaits conditions in form of lambdas rather than strings, so you have to refactor your code a little bit (just an idea below): IQueryable<CustCommPreference> query = _marketoEntities.CustCommPreferences.AsQueryable(); if (!string.IsNullOrEmpty(cusid)) query = query.Where(x => x.MasterCustomerID == cusid); if (!string.IsNullOrEmpty(mktid)) query = query.Where(x => x.MarketID == mktid); and later use it: ... join b in query ...

Categories : C#

Linq and group by clause
That's the expression that determines what will go in the output of the group by clause. You are actually not inspecting the whole output, but only the Keys, which are the same in the examples above, because the grouping is done by the same thing (box.BoxId). However, replace the last line: select q.Key; with select q; You will notice that: the group 1 by ... query will return an IGrouping<int, int> which will have all values set to 1 the group box by ... query will return an IGrouping<int, Box>, which will have all the boxId keys and, for each of them, the corresponding Box objects with respect to the grouping criteria.

Categories : Linq

Linq groupby with where clause
You have to order the items after the grouping as GroupBy does not keep order. Moreover, you select the wrong items. To select the groups use select f instead of select g. from g in trust.Documents where g.doc_type == "Minutes" group g by g.meeting_date into f // Groups the items g into groups called g orderby f.Key descending // Orders the groups by their key (which corresponds to g.meeting_date) select f // Selects the group I also would highly recommend you to rename your variables: from document in trust.Documents where document.doc_type == "Minutes" group document by document.meeting_date into documentGroup // Groups the items g into groups called g orderby documentGroup.Key descending // Orders the groups by their k

Categories : C#

How can I add in a where clause to a select in LINQ?
Specify where before the select: var result = from entry in feed.Descendants(a + "entry") let content = entry.Element(a + "content") let properties = content.Element(m + "properties") let text = properties.Element(d + "Text") let title = properties.Element(d + "Title") let partitionKey = properties.Element(d + "PartitionKey") where partitionKey.Substring(2, 2) == "03" && text != null select new Content { Text = text.Value, Title = title.Value };

Categories : C#

LINQ filtering in IEnumerable property breaks binding
Try adding .ToList() at the end of your Where clause. return DataManager.Data.Workers.Where(w => w.Gender == Gender.Male).ToList(); Binding to methods isn't allowed so what is probably happening is you are binding to the Count property instead of method. List contains the Count property whereas IEnumerable does not.

Categories : C#

How to create a list from filtering 2 lists with linq to object
With your requirement, I think we should use Any method, therefore we should write method query not expression query. Of course I don't know the equivalent of Any in expression query (At least it should be short as in the method query, otherwise, it's not good). If any one knows, please leave some comment. Thanks for that. var FilteredAList = ListOfA.Where(x=>ListOfB.Any(y=>x.Code==y.Code && y.Name=="yoda")) .ToList<A>();

Categories : C#

OR condition with ON clause in join in LINQ
It is not possible to write OR conditions in join with LINQ. Possible workaround is a cross join with WHERE clause: from tab1 in database.table1.getall() from tab2 in database.table2.getall() where tab1.field1 == tab2.field1 || tab1.field2 == tab2.field1 select new { tab1.field1, tab1.field2, tab1.field3, }

Categories : Linq

Where-clause for LINQ-to-NHibernate FetchMany?
Perhaps not exactly what you're after, but certainly worth considering is the NHibernate.CollectionQuery library. It allows you to query uninitialized NHibernate collections on an entity using Linq - but would require an additional query/round-trip to get them (unlike FetchMany, which grabs the entire collection in the same round-trip).

Categories : Linq

Linq to xml multiple group by clause
One thing in your attempt you have put account_id in both Keys... Also what is the "Key" object? As far as I know you do not need this and that might be the source of some of your errors Can you try the following: By i.Parent.Element("account_id").Value.ToString(), i.Parent.Element("payment_mnth").Value.ToString() EDIT: Ok I think that this is part due to me not being familiar with VB. I see what "Key" was for now so you can ignor that if you like. The reason for your error can be found at http://stackoverflow.com/a/4647477/1341477 To correct it you can do as follows: By AccountId = i.Parent.Element("account_id").VAlue.ToString(), PaymentMonth = i.Parent.Element("payment_mnth").Value.ToString() Into g = Group Select New With {AccountId, PaymentMonth, g.Sum()}

Categories : Misc

Need Help Filtering A LINQ Query Using An Entity Framework Navigation Property
You can do this fairly easily with the Where and Any methods: var results = dbContext.Employees.Where(e => e.EmployeeTypes.Any(et => et.Id == 2)); Or if you prefer query syntax: var results = from e in dbContext.Employees where e.EmployeeTypes.Any(et => et.Id == 2) select e;

Categories : C#

Using Linq for copying/filtering produces a dynamic result in foreach loops?
The .ToArray() solves the issues because it forces you to evaluate the entire enumeration and cache the local values. Without doing so, when you enumerate through it the enumerable attempts to calculate the first index, return that, then return to the collection and calculate the next index. If the underlying collection you're iterating over changes, you can no longer guarantee that the enumeration will return the appropriate value. In short: just force the evaluation with .ToArray() (or .ToList(), or whatever).

Categories : C#

How can i use a where clause within a select statement in linq. (ie. on a property.)
Something like this: Cato = c.dcKey == 6 ? c.totalOnHandQuantity : 0, Kerry = c.dcKey == 7 ? c.totalOnHandQuantity : 0 The ?: syntax is called a conditional operator.

Categories : C#

How do I build the following dynamic LINQ to Entities WHERE clause?
concatenate it in one query query.Where( s => ( ( title1!=null && episodeTitle1!=null && s.Title.Contains(title1) && s.EpisodeTitle.Contains(episodeTitle1) ) || ( title2!=null && episodeTitle2!=null && s .Title.Contains(title2) && s.EpisodeTitle.Contains(episodeTitle2) )

Categories : C#

LINQ query with array element in Where clause
I'd like to avoid filling my for loops up with things like... Unfortunately, that is typically the best option. The expression evaluation needs to be able to convert the expression tree into SQL, and it doesn't know how to handle array elements. Making temporary variables is the simplest, most maintainable way to handle this scenario.

Categories : C#

Passing null parameters into LINQ where clause
Using LinqPad you can see the difference. The former creates a query like: select ... from SomeTable as t0 where t0.SomeCol IS NULL whereas the latter is select ... from SomeTable as t0 where t0.SomeCol = @p0 Instead you can use object.Equals in your test. E.g., string test = null; var q = from c in SomeTable where object.Equals(c.SomeCol, test) select c; This will generate the appropriate where clause based on the value of the variable used in the condition.

Categories : C#

Generate Linq Or Clause from List of Enumeration
.Where is an extension method on IEnumerable < T >, which takes a predicate of type Func. Why not create a List < Func < T,bool > > ` with your predicates like x => x.AlphaValue, and when you have this list, iterate it and passing the values in a .Where on your IEnumerable? Hope i was able to tell you what i have in mind...

Categories : C#

Linq error when placing method in the where clause:
LinqToEntities will try to convert ALL of the criteria in the query to SQL. Since it can't directly convert getPrefixBySize to SQL, the entire query fails. You have a few options: Get more data than you need to and filter more using Linq-to-Objects: adminGalleryDesignerVM.Thumbnails = ( from tn in db.Media from fd in db.FileDescendants where tn.GalleryId == galleryId && fd.FileId == tn.FileId select new { id = tn.MediaId, FileName = tn.File.FileName, tn.FileId, fd.Prefix, Height = fd.FileHeight, Width = fd.FileWidth }) .AsEnumerable() // hydrate the query .Where(x => x.Prefix == FM.getPrefixBySize(x.FileId, 250, 250, 1) .Select(x => new FileVM { id = x.id,

Categories : Linq

query generated by LINQ removes where clause
I'm assuming you're using code-first to generate your database. What seems to be happening is you're adding a IS NOT NULL condition against a DB column that is not nullable, which EF appears to be optimizing away. If the DB column is not nullable, then having an IS NOT NULL WHERE clause makes no sense. If your DB column is nullable, but you want the model to require a value, then you may need to add another layer to separate your domain model from your database schema. EF is meant to model your data schema as closely as possible. If you want to apply business rules that differ from your data constraints, you may need to to that in your ViewModel (or whatever is appropriate for your architecture).

Categories : C#

LINQ where clause- compare collection of strings
Sounds like what you want is this: var items = SharedContext.Context.Items.GetAll(); IEnumerable<string> filterList = new List<string>(){"new", "old", "current"}; var filteredItems = items.Where(i => filterList.Contains(i.Type.ToLower())); If you're having issues with this, you might want to try using an array instead: string[] filterList = new string[] {"new", "old", "current"}; var filteredItems = items.Where(i => filterList.Contains(i.Type.ToLower())); Update: Here's another strategy which generates a filter expression dynamically: var filterList = new[] { "new", "old", "current" }; var param = Expression.Parameter(typeof(Item)); var left = Expression.Call( Expression.Call( Expression.PropertyOrField(param, "Type"), typeof(

Categories : C#

How to specify a literal field name in a LINQ Query where clause?
well if you want to Find by Id... don't use return query.SingleOrDefault(); (which will probably raise an exception, by the way) use return query.Find(id); By the way, to avoid strings, you could use public virtual TEntity GetByIdIncludingEntities(int id, params Expression<Func<TEntity, object>> [] entities) { var query = context.Set<TEntity>(); foreach (var entity in entities) query = query.Include(entity); return query.Find(id; } as there's an overload for Include which takes an Expression<Func<TEntity, TValue>> as parameter (you may have to import the correct namespace to get it). then usage would be repository.GetByIdIncludingEntities<Entity1>(id, m => m.RelatedEntity, m=> m.OtherRelatedEntity)

Categories : Linq

Linq query where clause returning null
You don't need to cast to string in where clause also you need to compare it against Value like where exp.Element("Posted_Status").Value == "Ready" Try: var expiration = from exp in main.Elements("Network") where exp.Element("Posted_Status").Value.Equals("Ready", StringComparison.CurrentCulture) select new { Timed_On = exp.Element("Timed_On").Value, Timed_Off = exp.Element("Timed_Off").Value, }; For Ouput: foreach (var item in expiration) { Console.WriteLine("Timed_On: {0} Timed_Off: {1}", item.Timed_On, item.Timed_Off ); } (Its better if you parse the values to a propert DateTime object)

Categories : C#

Linq Select Clause w/ Unknown Number of Fields
You could do it with dynamic type (nb, I did not test so this might have typos.): var query =dt.AsEnumerable().GroupBy(item => item.Field<string>("ID")) .Select(g => { dynamic t = new System.Dynamic.ExpandoObject(); if (g.Table.Columns.Any(c => c.ColumnName == "Status")) t.Status = g.Field<string>("Status"); if (g.Table.Columns.Any(c => c.ColumnName == "Disc")) t.Disc = g.Field<string>("Disc"); t.ID = g.Key; t.Loc = String.Join<string>(",",g.Select(i => i.Field<string>("Loc"))); return t; }

Categories : C#

linq query with dynamic predicates in where clause joined by OR
Thanks to Raphaël Althaus that gave the following link: http://www.albahari.com/nutshell/predicatebuilder.aspx Predicate builder is the solution. You can use it installing LinqKit from Nuget. In that url you can find also the implementation of this class. Note: in order to make this work with LinqToSql or LinqToEntities the IQueriable Object must be transformed using "AsExpandable()" method, for memory objects it's not required

Categories : Linq

LINQ Subquery in Where Clause returning error in LINQPad
It got resolved. Correct navigation route for the lines in error was: .Where(e => innerquery.Any(a => a.com_id == e.customer.application.com_id)) // exception at this line .Where(e => innerquery.Any(a => a.fnd_id == e.customer.application.fnd_id)) The error was due to e.advice.application

Categories : C#

Is Linq to Objects chaining where clause VS && performance hit is that insignificant?
Yes, it would be good advice to try to avoid chaining .Where() clauses on top of one another when it's a no-brainer and you have the opportunity, like in this microbenchmark. Note that .NET's LINQ-to-Objects implementation is smart enough to combine the predicates for you when you do this. It's not as bad as it could have been, but running the fancy chained delegate is not going to be as fast or as elegant as running a single delegate with all the logic inside of it. However, suppose you have an arbitrary instance of an IEnumerable<T>, which may or may not be the result of some .Where() method already, and you're writing a method that needs to filter it on some predicate. Based on the results of this microbenchmark, are you really going to refactor your entire code base so that y

Categories : C#

how to construct a dynamic LINQ to Entities ORDER BY clause?
You are using .OrderBy and .OrderByDescending incorrectly. The lambda expression used in these should produce a value for each item. Instead, you are producing the same value (whatever's in orderBy) for each item. You need to do something like this: Func<ItemType, object> orderByExpression; switch (orderBy) { case "Column1": orderByExpression = s => s.Column1; break; case "Column2": orderByExpression = s => s.Column2; break; ... default: throw new NotSupportedException(); } switch (order) { case "asc": query = query.OrderBy(orderByExpression); break; case "desc": query = query.OrderByDescending(orderByExpression); break; default: throw new NotSupportedException(); }

Categories : C#

LINQ-to-SQL query not returning row when where clause compares against NULL value
The first query doesn't behave as expected, because it is translated into SQL that is equivalent to the following: select * from RoleTable where Role != 'Admin' Now, in SQL NULL != 'Admin' is not TRUE (nor is it FALSE - it is undefined). That's one of the many cases where the abstraction that LINQ to SQL provides is leaky and you still need to know SQL. BTW: Your second query is also incorrect, it will select only those rows that are null. It wouldn't select a row with the role 'User'. The correct query would look like this: List<types> t2 = (from a in datacontext.RoleTable where a.Role != "Admin" || a.Role == null select a).ToList();

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.