w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
EF and LINQ querying by subcollection properties
var orderedFilms = Films.OrderBy(a=> a.Releases.Any() ? a.Releases.Select(x=>x.ReleaseDates.Any() ? x.ReleaseDates.Min(d=>d.Date).Date : DateTime.Now).Min() : DateTime.Now);

Categories : C#

Querying datatable.AsEnumerable with LINQ
It's not 100% clear from your question but it seems you are assuming that there will only be one row corresponding to any given parameters e.g A1, B0 etc. In your query you are using any() to determine if the list contains any elements and then trying to return Single() which will only work if there is only one element, so why are you using an Enumerable? It would be better to look for the first item that corresponds to your condition and put your conditions in the order you want e.g dtCh.AsEnumerable().OrderBy(Function(Row) Row.Field(Of Int64)("ID")).First(Function(Row) _ (Row.Field(Of String)("L_TYPE") = "A" And Row.Field(Of Int16)("Customer_Type") = 1) Or _ (Row.Field(Of String)("L_TYPE") = "B" And Row.Field(Of Int16)("Customer_Type") = 0)).Price EDIT: Ok I didn't quite get wh

Categories : Vb.Net

WCF error when querying using LINQ to Objects
After much trial and error, I have found that it is not a querying issue, it is a size issue. Though the WCF service was filtering my data to only return a few records, I guess it retained some sort of reference to the rest of the data because it errored with too much data. If I do a partial filter on the DAL and then continue to filter on WCF layer, coming out the same amount of records as I originally tried to return, it returns the list without a problem. I cannot explain why this happens, I don't know much about WCF, just explaining what I did to get around it in case anyone else has this problem.

Categories : C#

Querying XML elements with identical name with Linq
You can nest queries. var productTypes = from productType in xml.Elements("ProductType") select new { Name = productType.Attribute("Name").Value, Amount = Convert.ToInt32(productType.Element("Amount").Value), // How to get all Pattern elements from that ProductType? Patterns = from patt in productType.Elements("Pattern") select new { Length = int.Parse(patt.Attribute("Length").Value), .... } };

Categories : C#

Legacy collection querying before LINQ
Before LINQ you were just limited to all the built-in List/List<T> methods, and yes Find is one of them (still is). The difference is it expects a Predicate<T> as opposed to a Func<Boolean, T> which you can still do inline e.g. var found = list.Find(delegate(Item item) { return item != null; }); Or as you demonstrated by using a named method.

Categories : C#

Querying database schema with LINQ to SQL
The problem is that you don't have entities SchemaDataContext, so there are no mappings at all. But if you don't have entities in SchemaDataContext anyway, you really shouldn't use an ORM. Here is a simpler solution, without Linq to SQL: public static IEnumerable<string> GetTables() { using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); foreach (var table in connection.GetSchema("Tables").Rows) { yield return (string)table[2]; } } }

Categories : C#

Querying C# attribute
Well, what you want to accomplish is certainly possible, but it would not be an optimal use of the run-time or the MVC model. In this particular case, think of an attribute as an annotation. It's something you use to mark a function, controller, etc. so that its execution behaves differently at run-time. The attribute itself should not be doing the bulk of the work, rather just signalling to other pieces in your design to behave differently. It seems like you want to check some header values, and calculate something based off of that. You can use extension methods off of a Request class to accomplish this. Now, let's say that inside your Controller's function, you want to guarantee that the header values exist. You can have an attribute called RequireHeaderValues that implements IAction

Categories : C#

Querying against nested arrays
$ in tags.$.tag_name should help: db.users.find({'tags.posts.post_id':'000000'}, {'tags.$.tag_name':1}) EDIT: ok, I read your update. In this case I see a solution in aggregation framework. We can try build pipeline like this: db.col.aggregate( {$match: {'tags.posts.post_id':'000000'}}, {$unwind: '$tags'}, {$match: {'tags.posts.post_id':'000000'}}, {$group: {_id:'$_id', tags: {$push: '$tags'}}} ) result will be: { "_id" : ObjectId("5209f5e4ef21a864f6f6ed54"), "tags" : [ { "tag_name" : "java", "posts" : [ { "post_id" : "000000" }, { "post_id" : "111111" } ] }, { "tag_name" : "ruby", "posts" : [

Categories : Mongodb

Querying for nested objects in Parse
Found the answer to my question in the iOS guide. My searches for "nested" didn't find it. "Associations" did :). PFUser *user = [PFUser currentUser]; // Make a new post PFObject *post = [PFObject objectWithClassName:@"Post"]; [post setObject:@"My New Post" forKey:@"title"]; [post setObject:@"This is some great content." forKey:@"body"]; [post setObject:user forKey:@"user"]; [post save]; // Find all posts by the current user PFQuery *query = [PFQuery queryWithClassName:@"Post"]; [query whereKey:@"user" equalTo:user]; NSArray *usersPosts = [query findObjects];

Categories : IOS

Linq to Sql using a non-column attribute property in Association attribute
The message is quite clear. LINQ to SQL translates statements to SQL and you tried to use a property that doesn't map to a column, so it can't be translated to SQL. You'll have to retrieve the entities you want from the database then try to query them using LINQ to Objects, ie LINQ operations on the resulting lists or arrays. A better option is to rethink your design and find a way to retrieve only the data you need from the database and avoid processing the results on the client. Linq to SQL in this case prevented you from doing something really dangerous. It could have retrieved all the data and process them using your non-column attribute but that would create an enormous performance hit. Some naive LINQ providers actually do just that. Imagine retrieving 1000 objects from the databa

Categories : C#

Sequence contains no elements when querying XML file by attribute ID
n.Element("postCodeRegex") will return the first element of that type, and only its "territoryId" will be examined. instead replace the where clause with this this : where n.Elements("postCodeRegex").Any(element=>element.Attribute("territoryId").Value == isoCode) EDIT: Ok, so you wanted the matching postcoderegex item. I thought you wanted the first element that was bundled with a match. Then the solution is much easier. return (from n in xml.Descendants("postCodeRegex") where n.Attribute("territoryId").Value == isoCode select n.ToString();

Categories : C#

fetch documents from mongodb collection by querying nested dictionary in mongo
You can use the $exists operator and dot notation to do this, but you need to build up your query dynamically like this (in the shell): var user = 'abc'; var query = {}; query['user_details.' + user] = { $exists: true }; db.coll.find(query);

Categories : Python

Nested ajax with nested rendered attribute in JSF
It is most likely what your ManagedBean is not in ViewScoped or SessionScoped. When you post back to the bean, you are loosing rendered states. I suggest to change for the ViewScoped one. Not related : You should remove the action attribute from the h:form since JSF override it.

Categories : JSF

Set element attribute value in XML with Linq
You need to change the query where you're selecting the element to update, it should be: XDocument doc = XDocument.Load(@"config_path"); var element = doc.Descendants().Elements("add") .SingleOrDefault(x => x.Attribute("key").Value == "MDXQueryDirectory"); element.SetAttributeValue("value", txtMDXQueryDirectory.Text); doc.Save(@"config_path"); You should also be using XDocument rather than XElement when getting the file. Note: XDocument.Load(@"config_path") - should point to the location of your XML file. Currently it does not.

Categories : C#

How to get value of element via attribute in Linq
var d = new XmlDocument(); d.LoadXml("yuor document text"); d.ChildNodes.OfType<XmlElement>().SelectMany(root => root.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Options").SelectMany(options => options.ChildNodes.OfType<XmlElement>().Select (option => option.Attributes["number"].Value))).Dump(); It could be a little bit agly. Maybe better to use foreach's or use XPATH //options/option["number"] - (xpath query may be wrong)

Categories : C#

Get Obsolete attribute using Linq
I believe something like this is what you are looking for from type in YourAssembly from p in type.GetProperties() from m in type.GetMembers() let propertyAttributes = p.GetCustomAttributes(true) let methodAttributes = m.GetCustomAttributes(true) where propertyAttributes.Any(a => a.GetType() == typeof(ObsoleteAttribute)) || methodAttributes.Any(a => a.GetType() == typeof(ObsoleteAttribute)) select new type; It queries all types in an assembly and selects those which have properties or methods with the ObsoleteAttribute.

Categories : C#

Querying data results a lock on the querying table
If I'm not wrong SQL Server does not come with row versioning enabled by default, hence I think this is why you're seeing this behavior. What I suspect is when you issue a select query, and before this query finishes you issue another update query, the update has to wait until the select is complete. There are many approach to solve this problem, with one being enabling the row versioning. Other option include using the least restrictive isolation level.

Categories : Spring

LINQ vs nested loop
Will there actually be more objects created or does the C# compiler emit code resembling the nested loop with an if inside? More objects; each LINQ operation (SelectMany, Where, Select etc) will result in a new place-holder object that represents the pending IEnumerable<T> query of that operation, and then when it is finally iterated, each of those will result in an enumerator instance, along with the context etc. Plus there is a captured-variable context for the hoisted orderStorageId, etc. Note that the regular foreach will also result in an enumerator instance, but foreach has the advantage that it can also use duck-typed enumerators - which means that for things like List<T> it is actually using a struct enumerator, not a class enumerator. And of course using the loca

Categories : C#

LINQ to XML in VB - attribute name is reserved word?
- is a problem here. You have to put your attribute name in <>: Dim artistrels = From u In response...<relation-list> _ Where u.@<target-type> = "artist" Select ...

Categories : Vb.Net

Linq to XML query nested elements
You have to add Root property call (or Element("Users")) at the beginning of the query. You should use Elements instead of Descendants when you know where exactly the element is in tree structure. Why did you start querying for trans from the item instead of accts, which is already defined there? That one works and returns 3 items var userAcctInfo = from item in Data.Root.Elements("user") where (string)item.Attribute("usertype") == "Customer" && (string)item.Attribute("userID") == userId from accts in item.Elements("account") where (string)accts.Attribute("accounttype") == account from trans in accts.Elements("trans") select new Transaction((DateTime)trans.Attribute("tranDate"), (string)trans.Attribute("trantype"),

Categories : C#

Is this the best approach when using linq with a nested loop?
You should use GroupBy: var tiers = ActiveNodes.GroupBy(x => x.TierID); foreach (var t in tiers) { // Id for current group can be taken from t.Key property var tierId = t.Key; // t implements IEnumerable<Node>, so you can loop over it directly foreach(var n in t) { // do something } }

Categories : Linq

linq aggregated nested count
First, build a recursive method to count the Inner objects inside a Inner object including itself: public static int Count(Inner inner) { var count = 1; if (inner.Inners != null && inner.Inners.Any()) count += inner.Inners.Sum(x => Count(x)); return count; } Then you can order: var result = outers.OrderBy(o => o.Inners.Sum(i => Count(i)));

Categories : C#

Tricky LINQ and nested collection
This should be equivalent: db.Reports .Where(rpt => rpt.ID == reportId) .Cast<Report>() .SelectMany(rpt => rpt.SubReports) .SelectMany(subRpt => subRpt.SubReportItems) .ToDictionary( sri => sri.Title, sri => sri.SubReportItemNotes.SelectMany(note => note.NoteDetails); Notes: The first line of your code uses .Select(rid => rid.Id == reportId), but I assumed this should have been Where instead of Select, otherwise you would end up with a collection of null because the Select results would be of type bool and the as Report would output null for each. This only works if the Titles of all of your SubReportItems are unique. It is conceivable that one Report could have 10 SubReports and that among those SubReports there are two

Categories : Linq

Alternatives to nested Select in Linq
Because Points is a List you can take advantage of the fact that you can access each item by its index. So you can avoid comparing each item twice with something like this: var lst = from i in Enumerable.Range(0, Points.Length) from j in Enumerable.Range(i + 1, Points.Length - i - 1) where dist(Points[i], Points[j]) < minDistance select new { x = Points[i], y = Points[j] }; This will return a set composed of all points within minDistance of each other, but not exactly what the result you wanted. If you want to turn it into some kind of Lookup so you can see which points are close to a given point you can do this: var lst = (from i in Enumerable.Range(0, Points.Length) from j in Enumerable.Range(i + 1, Points.Length - i - 1) where dist

Categories : C#

Guid attribute returns wrong value when try to get it via Linq to XML
you want the value of the attribute: data.Attribute("guidNumber").Value

Categories : C#

LINQ - Join only one attribute with whole schema onf another entity
If you don't mind have extra parameter to hold the smtracks, then you can write like this :- select new { smtracks=tracksData , Tunecode = track_registrationData.TuneCode }; Later on you can get the value like smtracks.TracksID and so on.

Categories : Linq

Linq Groupby Sum a nested observable collection
You can use SelectMany to aggregate the items and group them afterwards: var result = responses .SelectMany(r => r.BoDPoints) .GroupBy(p => p.Date) .Select(byDate => new { Date = byDate.Key, EntriesByTime = byDate .GroupBy(p => p.Time) .Select(byTime => new { Time = byTime.Key, TotalVolume = byTime.Sum(p => p.Volume) }) }); You can use the following loop (e.g. to output the total volume) foreach (var byDate in result) { Console.WriteLine("Entries for date " + byDate.Date); foreach (var byTime in byDate.EntriesByTime) { Console.WriteLine("Total volu

Categories : C#

Acquiring all values of nested dictionaries that contain the same key using Linq
int key = 1; var query = test.Values // select inner dictionaries .Where(d => d.ContainsKey(key)) // which contain your key .Select(d => d[key]); // and return value by key Returns: "test1-1" "test2-1"

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

Transfor List to Nested Dictionary using linq C#
You can try this with a pair of GroupBy and a pair of calls of ToDictionary, like this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => h.Seelct(x => x.ID_OWNER).Distinct().Count()) ); If you would like to also add the total time per day, you can do this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => new { Count = h.Seelct(x => x.ID_OWNER).Distinct().Count()) , TotalTime = h.Sum(h => x.END_DATE-x.START_DATE) } );

Categories : C#

LINQ expression instead of nested foreach loop
Console.WriteLine(String.Join(Environment.NewLine, pro.TokenList.SelectMany(s => s) )); Or, Console.WriteLine(String.Join(Environment.NewLine, from arr in pro.TokenList from s in arr select s ));

Categories : C#

How/should I replace nested foreach with one linq query?
Controls.OfType<GroupBox> .SelectMany(x => x.Controls.OfType<Label>) .Where(x => x.Tag != null && x.Tag.ToString() == "answer") .ToList() .ForEach(x => x ForeColor = (x.Name.Replace("lbl", "") == rb.Name) ? afterSelectColor : beforeSelectColor); Notice that the ForEach() method is not part of LINQ. It's a member of the List<T> class. LinQ is a functional feature, therefore it's methods are not supposed to affect the source objects. That's why there's no ForEach() in LINQ. Edit: If you don't like the use of List<T>.ForEach(), then you may also do it this way: var labels = Controls.OfType<GroupBox> .SelectMany(x => x.Controls.OfType<Label>) .Where(x => x.T

Categories : C#

EF Linq Multiple Inner Joins using nested subqueries
So the following does the trick: from c in db.Contacts from co in c.Communities where co.Deleted == false select c Its all in the navigation properties when your using LINQ to Entities so the join is happening at "from co in c.Communities". I think my confusion was I was using LinqPAD which uses LINQ to SQL this link was helpful and made things clear for me: http://peter.hahndorf.eu/blog/post/2010/12/31/UsingLinqInManytomanySelectScenarios

Categories : Linq

Nested Select in LINQ with Lambda Expression
Any returns a bool, not a list of values. If you want a list of Newsflash ID's, you would use Newsflash.Select(x => x.Id) To get your list of messages that have a newsflash, you should use: var messages = (from m in Messages join n in Newsflash on m.Id equals n.Id select m).ToList(); This will join messages to your newsflash based on the Id for each, and then select the Message object that matches. alternative lamba syntax: var messages = Messages.Join(Newsflash, x => x.Id, y => y.Id, (x, y) => new { Message = x }).ToList();

Categories : Linq

Union two nested List with LINQ
It can be possible with LINQ with the help of SelectMany function. YOu can find the example of SelectMany Here

Categories : C#

c# linq select distinct of elements with multiple attribute
I want to return distinct tool and process attribute. It sounds like you want this this: var results = from e in apcxmlstate.Elements("thread") group e by Tuple.Create(e.Attribute("process").Value, e.Attribute("tool").Value) into g select g.First().Attribute("tool").Value; Or in fluent syntax: var results = apcxmlstate .Elements("thread") .GroupBy(e => Tuple.Create(e.Attribute("process").Value, e.Attribute("tool").Value)) .Select(g => g.First().Attribute("tool")); This will return the tool for each distinct tool / process pair—given your example set { "atool", "btool", "atool", "ctool" }. However, if all you want is distinct tool values you can just do this: var results = apcxmlst

Categories : C#

Linq select common subset of nested lists
You can use Enumerable.Intersect, for example: IEnumerable<string> commonSubset = allDevices.First().Interfaces; foreach (var interfaces in allDevices.Skip(1).Select(d => d.Interfaces)) { commonSubset = commonSubset.Intersect(interfaces); if (!commonSubset.Any()) break; } DEMO If you want to reuse it you could make it an extension method: public static IEnumerable<T> CommonSubset<T>(this IEnumerable<IEnumerable<T>> sequences) { return CommonSubset(sequences, EqualityComparer<T>.Default); } public static IEnumerable<T> CommonSubset<T>(this IEnumerable<IEnumerable<T>> sequences, EqualityComparer<T> comparer) { if (sequences == null) throw new ArgumentNullException("sequences"); if (!sequen

Categories : C#

Getting nested XML attribute value using XmlDocument
[Once you have an XmlNode object, you can ask for its Attributes collection and get the one you want by name. An example: XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlString); XmlNode itemNode = doc.SelectSingleNode("/error/item[@name = 'PATH_INFO']"); if (itemNode != null) { XmlNode value = itemNode.SelectSingleNode("value"); String valueString = value.Attributes["string"].Value; }

Categories : C#

LINQ to XML Select Nodes based on child node and attribute
string value = "232|4"; var xdoc = XDocument.Load(path_to_xml); var persist = xdoc.Root.Elements("Persist") .FirstOrDefault(p => p.Elements().Any(i => (string)i.Attribute("RoomCodes") == value)); Or with XPath extensions for LINQ to XML: var persist = xdoc.XPathSelectElement("//Persist[Item/@RoomCodes='257|1']");

Categories : Xml

Error in referencing parameters in nested lambda expression in LINQ ASP.NET
What you're really looking to do here is a Join. By joining the two tables you can find all of the students in one table that exist in the other. This is also an operation that can be done much more efficiently that what you're describing in which you search the entire set of data for each item. If it's known that you're doing a Join it can be very heavily optimized. var query = from student in students join foreignStudent in foreignStudents on new { student.FirstName, student.LastName } equals new { foreignStudent.FirstName, foreignStudent.LastName } into joinedStudents where joinedStudents.Count() > 0 select student;

Categories : C#



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