w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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 to Entities returning NULL when searching by GUID
All solution that could work in a scenario like this is to create a view and do just a one liner code to access it var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));

Categories : Entity Framework

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#

Why is this Linq function returning true when it is not?
because you have instantiated list in the constructor causing it not to become NULL. maybe you mean, list.Where(o => o.Badge == badge).Count() != 0

Categories : C#

LINQ Query returning result set twice
Shamelessly stealing Adam Maras comment and posting as an answer: What that means is that somewhere, later on in the page's lifecycle, something is calling ddlCountry.DataBind() again, which causes the control to add the contents of the data source to the list a second time.

Categories : C#

(Linq)Dictionaries: Except not returning a Dictionary
You're right that Except returns an IEnumerable(Of KeyValuePair(Of String, Type)). You could get around this by calling the ToDictionary extension method: a = a.Except(b) _ .ToDictionary(Function(x) x.Key, Function(x) x.Value) But this probably would be better, since it doesn't involve creating a new dictionary: For Each x in a.Intersect(b) a.Remove(x.Key) Next

Categories : Dotnet

Linq search not returning all entries
Short solution would be to include firstname and surname together in the where clause: var found = (from User in myDB.Memberships where User.Name.ToLower().Contains(txtSearch.Text.ToLower()) || User.Surname.ToLower().Contains(txtSearch.Text.ToLower()) || (User.Name + " " + User.Surname).ToLower().Contains(txtSearch.Text.ToLower()) However, this means a search for "Travolta john" wouldn't return any results. If this matters you should split up the string by spaces, and search for each word. List<string> searchSplit = txtSearch.Text.ToLower().Split(' '); var found = (from User in myDB.Memberships where IsMatch(searchSplit, User) private bool IsMatch(List<string> searchSplit, User User){ return searchSplit.Count() ==

Categories : C#

Returning empty linq expression
LINQ's equivalent of the SQL's 1=1 "thingy" is a predicate that always returns true: x => true Change your default method as follows: public virtual Expression<Func<CustomerCustomerType, bool>> WhereFilter { get { return x=>true; } }

Categories : C#

Linq to xml query not returning any values
You're not specifying the namespace in your Elements call. Fortunately this is easy in LINQ to XML: XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/directory/"; ... from el in root.Elements(ns + "User"); If you know that the ID attribute will always be an integer, I'd actually make that clear, and also avoid using a query expression when it doesn't help you: // TODO: Find a nicer way of doing this; you shouldn't need to parse it again XElement root = XElement.Parse(siteUsers.InnerXml); var siteUserElements = root.Elements(ns + "User") .Where(el => (int) el.Attribute("ID") == 814); foreach (XElement el in siteUserElements) { Console.WriteLine("el: " + el); }

Categories : C#

LINQ to EF returning all fields not just those in Select()
Hi, Could you please try below....? var query = from SubCat in mySubCategory where SubCat.CategoryID == 1 group 1 by SubCat.CategoryID into grouped select new { Catg = grouped.Key, Count = grouped.Count() }; Thank you, Vishal Patel

Categories : C#

Returning a maximum number of items the LINQ way
Your method is the best method. I would not make any changes at all. Any other option, such as querying the count alone first is performing what appears to be an expensive operation (doing the actual searching) twice in the event that you have less than 26 items. You save only a little tiny bit in the error case and add a significant expense in the common case. The only time your code would be less desirable is if _repository.Search(name) returned a type that could be cheaply iterated twice and that could cheaply provide it's count (like, say, a List) but in context that doesn't appear to be the case.

Categories : C#

C# simple Linq to XML query returning only 1 result
ResultsListBox.ItemsSource = from song in band.Descendants("song") select new Song { Name = song.Attribute("name").Value, Sum = song.Attribute("sum").Value, Number = song.Attribute("number").Value };

Categories : C#

LINQ and check for !=null
tableName.AsEnumerable() makes the query in-memory, so all table rows are downloaded from DB and the conditions are checked on application. Try that: var variableName = from a in tableName where a.column1 == item1 && a.column2 == item2 && a.column3 != null select a; It should be translated into an SQL query and download only necessary rows.

Categories : C#

Linq set null to a value with automapper
I will consider ResolutionMessageID is a nullable type, you can try something like this: .ForMember(dest => dest.ResolutionMessage, opt => opt.MapFrom(src => src.ResolutionMessageID.HasValue ? src.Messages.Where(m => m.MessageID == src.ResolutionMessageID) : null)); If it is not a nullable type and allow null: .ForMember(dest => dest.ResolutionMessage, opt => opt.MapFrom(src => src.ResolutionMessageID != null ? src.Messages.Where(m => m.MessageID == src.ResolutionMessageID.Value) : null)); Or you use opt.MapFrom() or opt.Ignore(), there is not way to use both. I think it is better keep the null value when the condition for you map does not accept the rule. If you use, opt.Ignore() will ignore the property on conversion of objects.

Categories : C#

Returning a multiple table LINQ query as one object
You have to initialize a Rule object and you can use FirstOrDefault if you want a single object: IEnumerable<Rule> rules = from ruleDefinition in AREContext.STRATRULEDEFs from ruleCodes in AREContext.STRATCODES where ruleDefinition.STRATRULEKEY == ruleKey && ruleCodes.STRATRULEKEY == ruleKey select new Rule { ruleDefinition = ruleDefinition, ruleCodeList = ruleCodes.ToList() }; Rule firstRule = rules.FirstOrDefault(); // can be null if rules is empty

Categories : C#

LINQ JOIN with multiple conditions returning error
solved by the following var participants = from b in _dc.WebProgramParticipants join d in _dc.webeventaffiliations on new { UserID = b.UserID, eventid = eid } equals new { UserID = d.userid, eventid = d.eventid } join c in _dc.WebPersonalInfos on b.UserID equals c.UserID where (b.eventid == eid) select new { b.ParticipantID, c.FirstName, c.LastName, c.Email, d.institution }; Ensure that types on both sides of the join conditions have the same Case. (for C# anyway)

Categories : C#

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#

Linq Query returning rows matching all words in array
This will go through your array and find the matching key for each element, if this is what you're looking for? var ids splitKeywords.Select(k => keywordSearchQuery.Single(q => q.Name == k).Id).ToArray(); You'd have to do a bit more validation if the Name wasn't unique or if you weren't sure you'd get a match.

Categories : C#

How to handle null in list<> when using linq
Try: public static string ToSeparator<T, TU>(this IEnumerable<T> source, Func<T, TU> func, string separator) { return string.Join(separator, source.Select(s => (s == null ? default(TU) : func(s)) .ToString()).ToArray()); } Note that in the case where your selector is "deeper" than the property on the parent type, ie: persons.ToSeparator(m => m.Address.ZipCode, "-"); This completely falls apart. Best to do the select first, handling the null similarly to how I did (maybe create another extension method for SelectNullOrDefault or something) and then pass THAT as the source to your ToSeparator method... Would be much safer.

Categories : C#

Passing null as Contains() within "linq to sql" query
You're building an IQueryable, which defines how to query for something, not actually doing it. To do this it builds an Expression, which defines all the query intents and can later be called to actually get the data. If you were using LINQ-to-Objects, this would likely work since it would likely call searchConditions.ActionIDs != null first, then know that it doesn't have to attempt to execute the second portion. Linq-to-Entities/SQL, etc. don't have that benefit. Long story short, you can either do: searchConditions.ActionIDs = searchConditions.ActionIDs ?? new int[]; Or do a different query if its null, like: var query = _dbContext.AuditTrails; if(searchConditions.ActionIDs != null && searchCondition.ActionIDs.Length != 0) { query = // Further filtered query where Acti

Categories : Linq

How to check in linq if the list is null?
You could change List<dataObject> lst = null; to List<dataObject> lst = new List<dataObject>; Or do something like this: public List<dataObject> GetAllCustomItems(CategoryType currType, int mCategoryID) { try { switch (currType) { case CategoryType.Dressing: List<dataObject> lst = (from xx in this.DressingItems where xx.DressingInfo.CatID == mCategoryID select new dataObject() { ID = xx.DressingInfo.DressingID, Name = xx.DressingInfo.Description, Selected = xx.IsDefault }).ToList(); break; } }

Categories : C#

Linq query may be null property is not
You could try to fill it with a default value of 0: (from a in dbContext.TableA join b in dbContext.TableB on a.IdB equals b.IdB into bLeft from bTbl in bLeft.DefaultIfEmpty() select new { IdBTemp = bTbl == null ? 0 : bTbl.IdB, IdATemp = a.IdA }.AsEnumerable().Select(row => new DynamicClassModel() { // Stuff here (convertion to string, concatanations and other stuff) }); But perhaps you want to use a int? instead. In that case use this: (from a in dbContext.TableA join b in dbContext.TableB on a.IdB equals b.IdB into bLeft from bTbl in bLeft.DefaultIfEmpty() select new { IdBTemp = bTbl == null ? (int?)null : bTbl.IdB, IdATemp = a.IdA }.AsEnumerable().Select(row => new DynamicClassModel() { // Stuff here (convertion to string, concatanations and other stuff

Categories : C#

How to dereference a string that might be null in LINQ
And even though comparedObjects.X is null it still throws a null reference exception for the comparedObject.X.Trim() expression. you better do a null check before the linq statement if(comparedObject !=null && !string.IsNullorEmpty(comparedObject.X)) { // your code goes here } below code (ci.X == null || ci.X == string.Empty) && (comparedObject.X == null || comparedObject.X == string.Empty) can change to string.IsNullorEmpty(ci.X) && string.IsNullorEmpty(comparedObject.X) And i would change code as below List<Guid> Ids = DataContext.Indexes.Where(ci => (string.IsNullorEmpty(ci.X) && string.IsNullorEmpty(comparedObject.X)) || ci.X == comparedObject.X.Trim()) .Select(ci => ci.Id).ToList();

Categories : C#

ASP.Net MVC Linq to Sql how to handle a null datetime
You can make your property Nullable public class x { public DateTime? nullableDate {get; set;} } This should fix your issue. The questionmark makes sure you can have Null in the nullableDate property

Categories : C#

How do I delete a row with a null foreign key using Linq-to-SQL?
To make sure that you also catch nulls, you could modify your query to look like this : select * FROM [tblOvrdImpVols] WHERE ([key1] = @p0) AND ([key2] = @p1 OR ([key2] is null and @p1 is null) )

Categories : C#

How do I "select null as "Column" Using LINQ in C#
Drop the as "null" and name the parameter, casting the null to its type: from t in table1 select new { t.field1, t.field2, t.field3, someField = (string)null, t.field4}

Categories : C#

Why is this returning a NULL
I bet this runs on a 64bit system and your code looks like this: int main() { char *str=get_str(); printf("received str %s with len %d ", str, strlen(str)); } char *get_str() { char *str; int slen=get_strlen(); str=(char *)malloc(sizeof(char)*slen); set_str(str); printf("returning str %s with len %d ", str, strlen(str)); return str; } To fix this, add the appropriate prototyping: char *get_str(); before the function's first usage. On (most?) 32bit systems pointer are 32bit wide, which is the same size as an int to which the compiler defaults the function as the prototpye is missing, so although using a wrong type the value gets pass back up successfully. The latter won't work anymore on a 64bit system as pointers (on most systems) are wider than a

Categories : C

Why isn't this returning null?
You should use isNaN(value); to check for NaN Because: console.log(NaN === NaN); // false! NaN is not equal to itself. This may seem weird but it makes sense if you think about the nature of NaN. Let's say you have this code: var a, b, c; // a = 0;oops a is still undefined so we'll get NaN if we do an operation with it b = 5; c = 6 if (a + b === a + c) { console.log("math error?"); } You don't want to come to the seeming conclusion that 5 === 6.

Categories : Javascript

@Value returning null
Are you passing valid value expressions? For properties placeholder you can use something like: @Value("${directory.extDirectory}") You can also use Spring EL and get all the goodness from it using the #{value} check the docs here Is also possible to assign a default value in case the property is not found @Value("${directory.extDirectory:defaultValue}")

Categories : Spring

WPF Linq to SQL Returning a Custom Object with Data Binding to DataGrid C# MVVM
That's not really how I would do this. Your first mistake is that although you have added an instance of your LINQResult class into the Resources section, it has no data in it because you never call the Create method. This is how I would achieve this: I access the database using Linq2SQL and fill custom data types like your example, but here's the difference... I have a view model class for each view. In the view model classes, I have all the properties that I want to display in the UI, whether they are collections or singular items. The view model classes implement the INotifyPropertyChanged interface (this is essential) through a base class. I have DataTemplates set up in App.xaml that link the various view models to views and then I can display a view in the UI like this: <Content

Categories : C#

how to compare null in join linq syntax
this might help you Var r=from a in DepartmentMaster Join b in DepartmentDetail on a.(x => (int?)a.ID) ?? 0 equals b.(y => (int?)b.ID) ?? 0 Select a.Code,b.Name

Categories : C#

How to write below sql query in linq c# where some of paramteres will be null sometimes
You could probably just check for null outside of your expression, like this: if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null)) { if (StakeBuyInIds != null) { objWaitingListUser = objWaitingListUser.Where( x => x.WaitingListTypeId == LocalWaitingListTypeId || (x.WaitingListTypeId == GlobalWaitingListTypeId && StakeBuyInIds.Contains((Int32)x.StakeBuyInId)); } else { objWaitingListUser = objWaitingListUser.Where( x => x.WaitingListTypeId == LocalWaitingListTypeId || x.WaitingListTypeId == GlobalWaitingListTypeId); } } You might also be able to do this: if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeI

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#

Iterate over non null entities in model using linq
I can't see how you can achieve this without using reflection at all. You could try the following : Get all the EF types in the assembly which hosts them e.g. var types = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == "NamespaceWhereEFEntitiesLive" select t; You may need to ply around a bit with the above query, but you get the idea. You can then iterate through the properties of AnimalModel, check whether the property is of any type returned in types. e.g. foreach(var prop in AnimalModelProperties) { if (types.Contains(prop.GetType()) } Note that the above for loop is a bit of a guess, but the pseudo-code should clarify what I'm looking to explain.

Categories : Asp Net Mvc

Dynamic Linq OrderBy null error
I've found the answer. Replace the OrderBy query in the System.Linq.Dynamic.DynamicQueryable class with the below. It will handle nulls in a property that is an object. public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { //This handles nulls in a complex object var orderingSplit = ordering.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); var sortField = orderingSplit[0]; var splitted_sortField = sortField.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (splitted_sortField.Length > 1) { sortField = "iif(" + splitted_sortField[0] + "==null,null," + sortField + ")"; } ordering = orderingSplit.Length == 2 ? sortField + " " + o

Categories : Dotnet

Preventing null exception with Linq associations
well, you could do u.Pin == null ? string.Empty : u.Pin.UserPin or, if you find it more readable, list.Select(u => { var pin = string.Empty; if (u.Pin != null) { pin = u.Pin.UserPin; } return new { Cell = new object[] { u.UserId.ToString(), u.UserName, u.Password, pin } }; });

Categories : C#

View returning null
You should use findViewById() only once in the right context. Three ways you could achieve this with your code: Change Activity to contain your GestureListener and the AsynkTask as inner classes and reference the field iv of your Activity Keep GestureListener and AsynkTask as standalone classes and add the MyImageView as parameter to their constructor. Construct the two instances for this two classes in onCreate() after the findViewById() Put GestureListener and AsynkTask as inner classes of MyImageView and add MyImageView as parameter to their constructor. When constructing the two instances from within MyImage just pass this. findViewById() is context sensitive. This means it searches for a view starting at the current context. If the current context is an Activity it searches thru t

Categories : Android

getResourceAsStream("abc.xml") returning null
Your code is working. All you need to do is to check if src/test/resources is on your classpath and you should be fine (Project properties -> java build path) I just recreated your scenario and it worked fine. //Both snippets should work (don't forget to prepend a slash if using getClass().getResourceAsStream) System.out.println(this.getClass().getClassLoader().getResourceAsStream("a/b/c/file.txt")); System.out.println(this.getClass().getResourceAsStream("/a/b/c/file.txt"));

Categories : Java

findFragmentByTag returning null
Try using the tag on the activity's FragmentManager directly. The complete reference of your example seems to be this. Follow this example with more details, you will see that the writer keeps track of tabs and their tag.

Categories : Android

LayoutParams returning null
Here tc.getLayoutParams() you haven't given it any params yet so it will return null. Maybe you meant descriptiontv.getLayoutParams() Edit Try changing params.leftMargin = 30; params.rightMargin = 30; to params.setMargins(30, 0, 30, 0); And change LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams)tc.getLayoutParams(); to LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

Categories : Android



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