w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Linq query to sort collection
Use ThenBy IOrderedEnumerable<ProgramVersionRecord> orderedList = LoanOptionsProgramVersionList .OrderByDescending(p => p.ProgramVersionConfigured) // configured has priority .ThenBy(p => p.Description) .ThenBy(p => p.Code);

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

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#

Linq query to get filtred main collection and each list in result in that collection
This should be done in View Model (or Dto) layer, first, define your view models: public class RestaurantVM { public int Id { get; set; } public string Name { get; set; } public City City { get; set; } public List<MealVM> Meals { get; set; } } public class MealVM { public int Id { get; set; } public string Name { get; set; } public DateTime Date { get; set; } public int Price { get; set; } public int Number { get; set; } public int Kind { get; set; } } Then you can write LINQ like below: var restaurantVMs = db.Restaurants .Include(rest => rest.Meals) .Where(rest => rest.City.Name == city) .AsEnumerable() .Select(r => new RestaurantVM(){

Categories : C#

Removing from collection based on values from another collection - Lambda/Linq
Removal has to be done with foreach (as LINQ isn't supposed to alter collections), but other than that you can fetch unwanted brands and then items to remove from carlist1 with LINQ: var carlist2Brands = carlist2 .GroupBy(c => c.Brand) .Select(g => g.Key) .ToArray(); var carsToRemove = carlist1 .Where(c => carlist2Brands.Contains(c.Brand)) .ToArray(); foreach (var car in carsToRemove) { carlist1.Remove(car); }

Categories : C#

linq query Unable to create a constant value collection within collection
Try this. This will remove the groups list from the LINQ query, but if your groupId is a Guid and a user can have multiple groups you will be sending a really big list of guids to the query. List<Group> groups = new UserBiz().Groups(AchaAuth.CurrentUserId); var groupsIds = groups.Select(i => i.GroupId).ToList(); var result = from HeadsupArticle article in ctx.HeadsupArticles where article.GroupId == item.GroupId && article.Active && (!article.DisplayFor || (article.DisplayFor && article.Groups.Any(g => g.GroupId == Guid.Empty || groupsIds.Contains(g.GroupId)

Categories : Linq

How to remove each item that appears in first collection from second collection using linq?
This does what you need var solution = list1.Except(list2); You can find more details about Except here, but the basic idea is: This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.

Categories : C#

How do you sort a parent collection and child collection of entities?
You can't sort inner collection (because you can't assign result of sorting to parent.Children property), but you can return anonymous objects with sorted parents and sorted children without including children in parent entity: return (from parent in m_Context.Parents orderby parent.Name select new { Parent = parent, Children = parent.Children.OrderBy(c => c.ChildInformation.Name) }).ToList(); Or retrieve parents and sort children in memory.

Categories : Misc

Nested collection created as array instead of collection
Look at the note about reverseRelation and using coffeescript (from: http://backbonerelational.org/#relations-reverseRelation): Note that if you define a relation (plus a reverseRelation) on a model, but don't actually create an instance of that model, it is possible initializeRelations will never get called, and the reverseRelation will not be initialized. This can happen when extend has been overridden, or redefined as in CoffeeScript. See setup. Then try using .setup as described here: http://backbonerelational.org/#RelationalModel-setup

Categories : Backbone Js

According to nature queue in collection always use CompareTo() method to sort element but in below programme it sort only first element why?
I don't think toString() will output in any particular order. toString() is implemented using the AbstractCollection.toString(), and that uses the collection's iterator. From the PriorityQueue doc: The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order Note that this SO question may be of further use.

Categories : Java

Android - Do I need to sort a collection for min and max?
No it doesn't have to be sorted. The method iterates over the entire collection. See the Java docs for the method!

Categories : Android

How sort an array in a collection
Assuming the items in your products array are unique, there isn't any easy server-side support for maintaining this array in sorted order as at MongoDB 2.4. Your best option given the nested arrays will be to sort the arrays in your application logic as appropriate (i.e. on insert/update, or on retrieval/display). Data Modeling Considerations If you need to do a lot of manipulation of nested array entries, you should consider flattening your data model to make it easier to work with. Your design goal with MongoDB should be to have a data model that is appropriate for your application use cases with acceptable performance balance between ease of inserting/updating/querying. You definitely do not have to model everything in a single collection/query if it doesn't make sense to do so, an

Categories : Mongodb

Get objects from collection with Linq
Well, how to go about this problem? First, you could create an index of all the values of To. Then, filter your sequence based on the From property... Something like: var tos = new HashSet<string>(collection.Select(item => item.To)); var filtered = collection.Where(item => !tos.Contains(item.From)); You might want to check, if creating a HashSet really works like this, or if you need to construct it differently... but you get the idea. Sets are efficient, if the tos gets rather long, since you will be checking this a lot...

Categories : C#

VB.net, How to sort collection items by value
As Collection.Add takes general object type and no specific type - sort is not possible. As objects need to be compared against each other to be sort, it will be like comparing oranges and apples. And Collection provides sorting by Key and not value. I think, you may have to extend the Collection class and implement the sort. you can move the items by using Insert and RemoveAt methods. And Just a thought/advice: if the values are of specific type, how about using some other data structure. Like dictionary for which you can sort by value as mentioned in this link

Categories : Vb.Net

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#

C#: Linq Reverse Collection failed
You need to assign the return value to an object Something like int[] collection1 = new int[] { 1, 2, 3, 4, 5 }; ObservableCollection<int> obColl1 = new ObservableCollection<int>(); foreach (var item in collection1) // initial order 1,2,3,4,5 { obColl1.Add(item); Console.WriteLine("Added {0} in ObservableCollection", item); } Console.WriteLine("Now reverse their order"); var ret = obColl1.Reverse(); //try the changes here and the line below. foreach (var item in ret) // still show 1,2,3,4,5 instead of 5,4,3,2,1 { Console.WriteLine("After reversing ObservableCollection: {0}", item); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); From Enumerable.Reverse Method you will see that it has a return type, so you need to assign that to an object.

Categories : Linq

Multiple Field Collection Sort
User Comparator for this. As compaarble provide functionality to sort on single type basis. here is link where you found when to use comparable and comapartor http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html Use multiple comparartor one for confidence public class ConfidanceComparator implements Comparator<ExpandedTerm> { @Override public int compare(final ExpandedTerm o1, final ExpandedTerm o2) { return new Double(o1.confidence).compareTo(new Double(o2.confidence)); } } one for support public class SupportComparator implements Comparator<ExpandedTerm> { @Override public int compare(final ExpandedTerm o1, final ExpandedTerm o2) { return new Double(o1.support).compareTo(

Categories : Java

How to add TimeSpans together using LINQ when in a Dictionary collection
You can do it with the Aggregate LINQ method like this: var totalTime = myDictionaryStringTimeStamp .Values .Aggregate(new TimeSpan(0), (p, v) => p.Add(v));

Categories : C#

Creating an observable collection using linq to XML
I had a couple of problems here. First thing first I needed to make sure I wasn't mixing up Query syntax and Extension Methods syntax enter link description here Although in the above example I wasn't doing that, in my zeal to fix my problem I ended up doing that. Also, I had a comma at the end of my select statements. Anyway, in the end, I did this... patsModel = (ObservableCollection<PatientModel>) //from templateData in xDocument.Element("TemplateData").Elements("ACOData") .Select( template => new PatientModel { EncounterId = ValueOrMin(Convert.ToInt32(template.Element("FOCUSED_READMISSIONS_ID").Value)), PatientId = ValueOrMin(Convert.ToInt32(template.Element("PATIENT_ID").Value)

Categories : Misc

Backbone sort collection array
The models array is an array of Model objects, the attributes of which are stored in model.attributes. Wrapping the array and calling sortBy assumes the objects being sorted are plain objects, and the attribute directly accessible as model.{attribute}. To get it to do what you want you can pass sortBy a comparator function that gets the attribute you want: this.hotels.models = _(this.hotels.models).sortBy(function(model) { return model.get("order"); }); However this is what Backbone already does in the Collection class. To use the built-in comparator you can simply set the Collection's comparator attribute to the name of the Model attribute by which you want to sort. Example: this.hotels.comparator = "order"; this.hotels.sort(); $(this.el).html(this.template({hotels: this.hotels.

Categories : Backbone Js

How to sort a collection using the last element of an array
You can do this with the aggregation framework in the following way: db.so.aggregate( [ // first we add the ``sortr`` field so that we can deal with empty arrays. // if we see an empty array, we create one with a large negative number { $project: { value: 1, r: 1, sortr: { $cond: [ { $eq : [ '$r', [] ] }, [ -100000 ], '$r' ] } } }, // then we unwind on our sorting-r-variant { $unwind: '$sortr' }, // so that we can group by ID and pick out the last of the $sortr values { $group: { _id: '$_id', value: { $first: '$value' }, r: { $first: '$r' }, sortr: { $last: '$sortr' } } }, // then we sort by the last items over all the documents { $sort: { sortr: 1 } }, // and reproject so t

Categories : Mongodb

Handling hierarchical collection with Linq
It would be easier to use this Node class. Node<MenuElement> rootNode = <Any node of the collection>.Root; var mandatoryNodes = rootNode.SelfAndDescendants.Where(n => n.Value.IsMandatory); foreach (var mandatoryNode in mandatoryNodes) { foreach (var node in mandatoryNode.SelfAndAncestors.Reverse()) // Reverse because you want from root to node { var spaces = string.Empty.PadLeft(node.Level); // Replaces: for(int i=0; i<node.HierarchicalLevel; i++) space = String.Concat(space, " "); Console.WriteLine("{0}{1}. {2}", spaces, node.Value.Position, node.Value.Label); } }

Categories : C#

java collection sort issue
If two values x and y have the same openTime, then compare(x, y) and compare(y, x) will both return 1, which violates the contract of compare: The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. You haven't ensured that. You need to consider what you want to happen when the openTime values are the same - either return 0, or have some consistent notion of which value should come before the other. Do you have some secondary comparison you could perform, for example?

Categories : Java

linq sub list vb.net, sort by sub value
Ok I got it in the end... myList.OrderBy(Function(x) x.id).ThenBy(Function(x) If(x.listOfNiveau2.Any(Function(y) y.value = "Value2"), 0, 1)) you can substitute "Value2" with a variable and it should work. Just in case... it works by ordering on Int32 (either 0 , 1) which is determined by seeing if the List contains any niveau2 with a value that you passed in. I have tested it and it seems to work fine. Let me know if you have any problems. I can forsee that a list which is not sorted first by Id will return the items out of order therefore I have added the OrderBy.ThenBy as well.

Categories : Vb.Net

How do you tell Mongo to sort a collection before limiting the results?
The problem is that you need to sort on date instead of $date. myCollection.find().sort({date: 1}).limit(50, callback); Mongo applies the sort before limiting the results regardless of the order you call sort and limit on the cursor. Proof in docs: link

Categories : Mongodb

Can I combine a LINQ and a foreach that I use to add objects to a collection?
Yeah you can do this way - objectiveDetail1.Where(a => objectiveDetail2.All( b => b.ObjectiveDetailId != a.ObjectiveDetailId)) .ToList().ForEach(_uow.ObjectiveDetails.Add);

Categories : C#

How to sort Symfony2 form collection items
You should use FormEvents::PRE_SET_DATA instead. Because after FormEvents::POST_SUBMIT the data you set doesn't get set to the form data again. Therefore you don't see the changed data. Please look at https://github.com/symfony/Form/blob/master/Form.php to see which form event is dispatched after which operations. Also have a look at official form events documentation. http://symfony.com/doc/current/components/form/form_events.html

Categories : Forms

Meteor: How can I sort a collection on a session variable?
Placing Session.get('sortby') directly in sort specifier will give a syntax error. Use an if-else block before the query to find out which value the Session contains, and put that field-name in query instead of Session.get() like: if( Session.equals('sortBy', 'profile_email') ){ return Meteor.users.find({}, {sort:{'profile_email':Session.get('sortorder')}}); } else if( Session.equals('sortBy', 'other_value') ) { return Meteor.users.find({}, {sort:{'other_value':Session.get('sortorder')}}); }

Categories : Javascript

Linq observable collection cast error
One common issue I've run into when dealing with Collections and passing a Linq result into them is the collection is not enumerated and enumerating it through a call to ToList often fixes the issue. I would give that a go and see if it helps. ObservableCollection<ListBoxItem> selectedcollection = new ObservableCollection<ListBoxItem>( unselectedcollection.AsEnumerable() .Where(item => item.Name == "firstName" || item.Name == "secondName" || item.Name == "thirdName") .ToList());

Categories : C#

Does backbone sort all elements in collection or just added ones
Just to be sure, is your collection sorted automatically because you defined a comparator function? I tried reading through the Backbone and Underscore source to determine the sorting method used. Unfortunately I couldn't make it out after 10 minutes of reading, so I can't figure out if a low-performance sort method is used. Still, I'm skeptical that the sorting is your major slowdown. In my experience, collection speed issues usually came from views re-rendering from add and update events. 2 is very possible by combining your idea with 1, just add new models to an array and use _.debounce to add the array to the collection every 500 ms. Be sure that the function you pass to debounce also clears out the array.

Categories : Javascript

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 properly sort a backbone js collection after fetch()
I think you might be better to listen to the "sync" event on the collection rather than the "add" event. The "add" event will probably get called as individual items are added to the collection and they may not be added in the order that they will eventually be sorted. So try changing the listenTo line to: this.listenTo(items, 'sync', this.addItems); Then your addItems function could be re-written as: addItems: function(items) { $("#item-list").empty(); items.each(function(item) { var view = new ItemView({model: item}); $("#item-list").append(view.render().el); }); }

Categories : Javascript

Update property in object collection with linq
LINQ is not the right tool to modify collections, it is a tool to query collections. If you want to modify it you need a loop, for example a foreach: var schedule = data.Select(d => new Schedule{ ID = d.id }).ToList(); foreach(var s in schedule) s.Name = "Condition Name"; If you want to "modify" a collection with LINQ you have to create a new one and assign that to your variable which is inefficient.

Categories : C#

Select not matched record from two collection using linq
You need the Except method: var yourResult = col1.Except(col2); If both of your collections aren't the same type, then you're going to have to do a more expensive O(nm) search: var selectedTwo = col2.Select(x => x.ID).ToHashSet(); var yourResult = col1.Where(n => !selectedTwo.Contains(n.ID)); And somewhere else in your code: public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) { return new HashSet<T>(source); }

Categories : C#

The method or operation is not implemented in collection using LINQ
Try converting into Tolist(). //Code fieldFormatDropDown.DataSource = (From FieldFormatLinq In fieldFormatsCollection Where FieldFormatLinq.DataTypeId = dataTypeId And FieldFormatLinq.IsActive = True).ToList()

Categories : Dotnet

Java - Collection.Sort over Interface Objects
Match the Comparable type with the class: public abstract class TypeOfMapObject extends IrrelevantClass implements Serializable, MapObject, Comparable<TypeOfMapObject> { @Override public int compareTo(TypeOfMapObject m) { //specific algorithm for natural ordering } } Or simply don't define the compareTo method in your abstract class - leave it for the subclass to implement. To address edit to question: If you want to compare different subtypes, have them implement a method that returns a value (say String) with which they may be compared. For example: public abstract class TypeOfMapObject extends IrrelevantClass implements Serializable, MapObject, Comparable<TypeOfMapObject> { @Override public int compareTo(TypeOfMapObject m) {

Categories : Java

Using LINQ to pull collection until aggregate condition met
pragmatic approach int needed = ...; int actual = 0; int page = 0; const int pagesize = 20; // set to some sensible value, eg. the pagesize of the grid shown to the user var results = new List<CookieOrder>(); while (actual < needed) { var partialResults = session.Query<CookieOrder>() .Where(c => c.Name == "Snickerdoodle") .OrderBy(c => c.Id) .Skip(page * pagesize) .Take(pagesize) .ToList(); for(int i = 0; i < partialResults.Length && actual < needed; i++) { results.Add(partialResults[i]); actual = partialResults[i].Quantity; } page++; } return results;

Categories : SQL

MVC LINQ Sort / OrderBy a Model
If PickupDistanceSort is not a .Net type you need to imlement an IEqualityComparer for your type and use OrderBy like this (PickupDistanceComparer is the name of your custom comparer): model = mode.OrderBy(s => s.PicupDistanceSort, new PickupDistanceComparer());

Categories : C#

How to sort in linq to sql for a joined table?
Assuming you've got appropriate navigation properties set up, something like this should work: var results = (from a in dc.RPGs where !a.IsHided && !a.IsDeleted orderby a.Characters.SelectMany(c => c.Posts).Select(p => p.Timestamp).Max() select a) .ToList(); Or possibly: var results = (from a in dc.RPGs where !a.IsHided && !a.IsDeleted orderby a.Characters .SelectMany(c => c.Posts) .OrderByDescending(p => p.Timestamp) .Select(p => p.Timestamp) .FirstOrDefault() select a) .ToList();

Categories : Asp Net

How to combine collection of linq queries into a single sql request
Well, for performance considerations, I would change the interface from IEnumerable<T> to a collection that has a Count property. Both IList<T> and ICollection<T> have a count property. This way, the collection object is keeping track of its size and you just need to read it. If you really wanted to avoid the loop, you could redefine the RecordCount to be a lazy loaded integer that calls GetViewSpecificQuery to get the count once. private int? _recordCount = null; public int RecordCount { get { if (_recordCount == null) _recordCount = GetViewSpecificQuery(view.CustomFilters).Count; return _recordCount.Value; } }

Categories : Linq



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