I have an IEnumerable for multiple sort order specification where:  public class Specification {     public string Column { get; set; }     public OrderByDirection Direction { get; set; }     public int Priority { get; set; } }      Then I have another IQueryable that I would like to lazy sort on the basis of the given IEnumerable respecting the direction and the priority. What would be the best approach to do this? are there any libraries out there that currently do this? Can someone explain how something like this can be approached with dynamic queries (expression trees)?  Note: Assume the column specified do exist in the IQueryable.
11195
I found an example in the  for Dynamic LINQ that allows you to use a sql-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable&lt;T&gt;. Is there any way to get this functionality on IEnumerable&lt;T&gt;?
36213
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL: SELECT f.*  FROM Foo f WHERE f.FooId IN (     SELECT fb.FooId     FROM FooBar fb     WHERE fb.BarId = 1000 )  Any help would be gratefully received.
104755
I have a gridview and I need to sort its elements when the user clicks on the header. Its datasource is a List object.  The aspx is defined this way :  &lt;asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false"      AutoGenerateColumns="false" Width="780" runat="server"  OnSorting="grdHeader_OnSorting" EnableViewState="true"&gt;     &lt;Columns&gt;         &lt;asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" /&gt;         &lt;asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" /&gt;         &lt;asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" /&gt;     &lt;/Columns&gt; &lt;/asp:GridView&gt;   The code behind is defined this way : First load :  protected void btnSearch_Click(object sender, EventArgs e) {     List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection();     this.grdHeader.DataSource = items;     this.grdHeader.DataBind(); }   when the user clicks on headers :  protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) {     List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection();     items.Sort(new Helpers.GenericComparer&lt;V_ReportPeriodStatusEntity&gt;(e.SortExpression, e.SortDirection));     grdHeader.DataSource = items;     grdHeader.DataBind(); }   My problem is that e.SortDirection is always set to Ascending. I have webpage with a similar code and it works well, e.SortDirection alternates between Ascending and Descending.  What did I do wrong ?
67080
I have a table with 5 columnsID,CPT4,CPT4Mod,ItemCharge,Eff_Date.   Deletion Condition:  When rows exists with duplicate CPT4and CPT4Mod field values but different ItemCharge and Eff_Date values, exclude all but the most recent Eff_Date records.  I need a query which can achieve this in two scenarios.   When CPT4Mod is given by the user. When  CPT4Mod is not given by the user.   Later I need to achieve the same using LINQ.
123190
I have a List&lt;int&gt; and a List&lt;customObject&gt;. The customObject class has an ID property. How can I get a List&lt;customObject&gt; containing only the objects where the ID property is in the List&lt;int&gt; using LINQ?  Edit: I accepted Konrads answer because it is easier/more intuitive to read.
4278
Is there a quick and nice way using linq?
54579
Is there a tool out there which can convert SQL syntax to LINQ syntax?   I just want to rewrite basic queries with join, etc., to . It would save me a lot of time.
429
I have a wrapper class which contains a list of sobjects, i want to have th sorting on the fields of these objects in the wrapper list: The apex code is as follows:  Class jobsWrapper {     public JobSuite__Job__c job { get; set; }     public JobSuite__Job_Task__c jobTasks { get; set; }      public JobsWrapper(JobSuite__Job__c objjobs, JobSuite__Job_Task__c objjobTasks) {         // if(jobTasks== NULL){jobTasks = new List&lt;Job_Task__c&gt;();}         job = objjobs;         jobTasks = objjobTasks;      }      public JobsWrapper() {         if(jobTasks== NULL) {             jobTasks = new JobSuite__Job_Task__c();         }          if(job == NULL) {             job = new JobSuite__Job__c();         }             } }   I want to allow sorting the wrapper list by the fields in the job - like client, jobname, jobnumber etc and fields from the task object as taskname, reviseddue dateetc.  How can I do this? Please help, thanks in advance.
22294
We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.  Users can define their own sort, basically choosing what column to sort by.  Columns are dynamic - some have numeric values, some dates and some text.  While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.  For instance, sorting by a string record id gives something like:  rec1 rec10 rec14 rec2 rec20 rec3 rec4   ...and so on.  I want this to take account of the number, so:  rec1 rec2 rec3 rec4 rec10 rec14 rec20   I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".  I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.  Does anyone know a way to quickly apply a natural sort in Sql server?    We're using:  ROW_NUMBER() over (order by {field name} asc)   And then we're paging by that.  We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.    We have valid user input that follows different formats for different clients.  One might go rec1, rec2, rec3, ... rec100, rec101  While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301  When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.  These formats vary a lot, but are often mixtures of letters and numbers.  Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn.  However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.  SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.  @moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.
20851
How can one programmatically sort a union query when pulling data from two tables? For example,  SELECT table1.field1 FROM table1 ORDER BY table1.field1 UNION SELECT table2.field1 FROM table2 ORDER BY table2.field1   Throws an exception  Note: this is being attempted on MS Access Jet database engine
48401
Okay, I have ran in to a problem with VB.NET. So all those defenders of VB.NET please can you help me out? Here is my issue: I am using LINQ to Entities, it also works with LINQ to SQL, I build my edmx file I then create a Partial Publc Class of the same name as one of the entities All fine up to now, so here comes the problem.   I need the Partial class to implement an Interface Implements Interfaces.IAsset But VB.NET want to place "Implements Interfaces.IAsset.ID" at the end of the property, which of course is in the generated code section of the Partial class, which I can not do as the edmx file is auto generated and will change in the future.   Here is the line of code that needs sorting:   Public Property ID1() As Integer Implements Interfaces.IAsset.ID   In C# it is fine and works wonders. So why can't VB.NET implement an interface that is in the code generated class?
117430
I was wondering if anyone has a good solution to a problem I've encountered numerous times during the last years.  I have a shopping cart and my customer explicitly requests that it's order is significant. So I need to persist the order to the DB.  The obvious way would be to simply insert some OrderField where I would assign the number 0 to N and sort it that way.  But doing so would make reordering harder and I somehow feel that this solution is kinda fragile and will come back at me some day.  (I use C# 3,5 with NHibernate and SQL Server 2005)  Thank you
35972
Say I have a list of all Projects, and that I group them by Category like this:  var projectsByCat = from p in Projects                     group p by p.Category into g                     orderby g.Count() descending                     select new { Category = g.Key, Projects = g };   Now I want to display this as a list in a web page, where first I create the left side div, secondly the right side div. I am ordering by number of Projects in each Category to show the Categories with the most Projects on top - thus I would like to split projectsByCat in two - if I put all the "odd numbered" Categories on the left and the "even numbered" categories on the right, I think I will get a reasonably sane view.  So I thought I could do this to get the odd and even members of projectsByCat:  var oddCategories = projectsByCat.Where((cat, index) =&gt; index % 2 != 0);  var evenCategories = projectsByCat.Where((cat, index) =&gt; index % 2 == 0);   And it compiles - however, when I run it, I get an exception such as this:     Unsupported overload used for query operator 'Where'.   And I thought I was safe since it compiled in the first place.. ;)  Is there an elegant way to do this? And also, is there an elegant explanation for why my creative use of Where() won't work?  Thanks in advance!
650
What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.
58140
I have a common scenario in app design, where I need to store an ordered list, and make the ordering easily accessible and adjustable via an application UI.    The ordering operations are simple and operate on only one item at a time - move to top, move to bottom, move up one position, or down one position.  These positioning operations may be interspersed in with typical add / edit / delete list operations.  For discussion, this is a single-user app and db store.  Because the objects can be highly complex, I'd like to avoid caching the entire list client-side, and tracking newly created objects in memory until a big save operation occurs.    I am using MS-SQL almost exclusively on these projects, and I'm wondering if there are db features, SQL features, or design patterns I should be using to better support the management of ordered lists.    My current approach is to use a DECIMAL column to store the list positions, which become fractional during the item move process.  Then I sort the list and re-generate integer positions to normalize list.  Following this operation, it's ready for another item move.   In an example implementation, I create a column named Seq for position tracking.  Once decimal place is enough for the .5 storage.   [Seq] [decimal](10, 1) NOT NULL   When an item is re-positioned in the app UI,    I UPDATE that record with new Seq value I retrieve the full table, sorted ascending by Seq and regenerate all Seq values in the table from a 1-based integer series   The new Seq value is easily calculated-    Move to top = 0 Move to bottom = MAX(Seq) + 1 Move up = subtract 1.5 from the current Seq value Move down = add 1.5 to the current Seq value   As lists get longer, updates get slower, since I'm doing N UPDATE statements, where N is the number of rows in the table, so it seems only suitable for small tables.    Is there some kind of in-built capability for managing an ordered list in SQL or MS-SQL? Is there a means to update multiple rows in one call?    A far more performant approach would be to allow more decimal places, and then position at the median of the two adjacent items, with no re-sequencing on the list.     Move to top = Min(Seq) - 1 Move to bottom = MAX(Seq) + 1 Move up = median of the 2 previous item Seq values Move down = median of the 2 following item Seq values   This approach only requires one SELECT (containing 2 rows max) and one UPDATE.    However with enough re-positions I imagine the field would run out of decimal places. For example, if I start with items at positions 10 and 11, and keep moving items down the list from position 9, they'd be given sequences of 10.5, then 10.25, then 10.125.  After 10 moves, the positions get lengthy... 10.0009765625.    UPDATE #1 - IMPROVED RE-SEQUENCING OF THE LIST  Regarding re-sequencing, I'm more caught up on row_number(), OVER, and WITH capabilities in MS-SQL.  It's nice to find that there's a much smoother way to re-sequence the list in a single UPDATE operation;  with OrderedItems as  (     select         ItemID,         Seq,         row_number() over (order by Seq asc) NewSeq     from          Items ) update OrderedItems set Seq = NewSeq
52342
I need to randomly 'sort' a list of integers (0-1999) in the most efficient way possible.  Any ideas?  Currently, I am doing something like this:  bool[] bIndexSet = new bool[iItemCount];  for (int iCurIndex = 0; iCurIndex &lt; iItemCount; iCurIndex++) {     int iSwapIndex = random.Next(iItemCount);     if (!bIndexSet[iSwapIndex] &amp;&amp; iSwapIndex != iCurIndex)     {         int iTemp = values[iSwapIndex];         values[iSwapIndex] = values[iCurIndex];         values[iCurIndex] = values[iSwapIndex];         bIndexSet[iCurIndex] = true;         bIndexSet[iSwapIndex] = true;     } }
76127
I have to maintain a large number of classic ASP pages, many of which have tabular data with no sort capabilities at all. Whatever order the original developer used in the database query is what you're stuck with.  I want to to tack on some basic sorting to a bunch of these pages, and I'm doing it all client side with javascript. I already have the basic script done to sort a given table on a given column in a given direction, and it works well as long as the table is limited by certain conventions we follow here.    What I want to do for the UI is just indicate sort direction with the caret character ( ^ ) and ... what?  Is there a special character that is the direct opposite of a caret?  The letter v won't quite cut it.  Alternatively, is there another character pairing I can use?