Search Results

Search found 6252 results on 251 pages for 'linq expressions'.

Page 15/251 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Retrieving only the first record or record at a certain index in LINQ

    - by vik20000in
    While working with data it’s not always required that we fetch all the records. Many a times we only need to fetch the first record, or some records in some index, in the record set. With LINQ we can get the desired record very easily with the help of the provided element operators. Simple get the first record. If you want only the first record in record set we can use the first method [Note that this can also be done easily done with the help of the take method by providing the value as one].     List<Product> products = GetProductList();      Product product12 = (         from prod in products         where prod.ProductID == 12         select prod)         .First();   We can also very easily put some condition on which first record to be fetched.     string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };     string startsWithO = strings.First(s => s[0] == 'o');  In the above example the result would be “one” because that is the first record starting with “o”.  Also the fact that there will be chances that there are no value returned in the result set. When we know such possibilities we can use the FirstorDefault() method to return the first record or incase there are no records get the default value.        int[] numbers = {};     int firstNumOrDefault = numbers.FirstOrDefault();  In case we do not want the first record but the second or the third or any other later record then we can use the ElementAt() method. In the ElementAt() method we need to pass the index number for which we want the record and we will receive the result for that element.      int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };      int fourthLowNum = (         from num in numbers         where num > 5         select num )         .ElementAt(1); Vikram

    Read the article

  • What can map database tables like LINQ to SQL did?

    - by trnTash
    A good thing in LINQ to SQL was a fast and reliable way to map database tables and convert them into classes accessible from c# project. However it is no longer recommended to create projects using LINQ to SQL. What is its substitute? What kind of tool should I use in VS 2010 today if I want to have the same functionality as I had with LINQ to SQL?

    Read the article

  • Retrieving recent tweets using LINQ

    - by brian_ritchie
    There are a few different APIs for accessing Twitter from .NET.  In this example, I'll use linq2twitter.  Other APIs can be found on Twitter's development site. First off, we'll use the LINQ provider to pull in the recent tweets. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: public static Status[] GetLatestTweets(string screenName, int numTweets) 2: { 3: try 4: { 5: var twitterCtx = new LinqToTwitter.TwitterContext(); 6: var list = from tweet in twitterCtx.Status 7: where tweet.Type == StatusType.User && 8: tweet.ScreenName == screenName 9: orderby tweet.CreatedAt descending 10: select tweet; 11: // using Take() on array because it was failing against the provider 12: var recentTweets = list.ToArray().Take(numTweets).ToArray(); 13: return recentTweets; 14: } 15: catch 16: { 17: return new Status[0]; 18: } 19: } Once they have been retrieved, they would be placed inside an MVC model. Next, the tweets need to be formatted for display. I've defined an extension method to aid with date formatting: .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: public static class DateTimeExtension 2: { 3: public static string ToAgo(this DateTime date2) 4: { 5: DateTime date1 = DateTime.Now; 6: if (DateTime.Compare(date1, date2) >= 0) 7: { 8: TimeSpan ts = date1.Subtract(date2); 9: if (ts.TotalDays >= 1) 10: return string.Format("{0} days", (int)ts.TotalDays); 11: else if (ts.Hours > 2) 12: return string.Format("{0} hours", ts.Hours); 13: else if (ts.Hours > 0) 14: return string.Format("{0} hours, {1} minutes", 15: ts.Hours, ts.Minutes); 16: else if (ts.Minutes > 5) 17: return string.Format("{0} minutes", ts.Minutes); 18: else if (ts.Minutes > 0) 19: return string.Format("{0} mintutes, {1} seconds", 20: ts.Minutes, ts.Seconds); 21: else 22: return string.Format("{0} seconds", ts.Seconds); 23: } 24: else 25: return "Not valid"; 26: } 27: } Finally, here is the piece of the view used to render the tweets. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: <ul class="tweets"> 2: <% 3: foreach (var tweet in Model.Tweets) 4: { 5: %> 6: <li class="tweets"> 7: <span class="tweetTime"><%=tweet.CreatedAt.ToAgo() %> ago</span>: 8: <%=tweet.Text%> 9: </li> 10: <%} %> 11: </ul>  

    Read the article

  • Lambda Expressions

    - by Asad Khan
    Can somebody explain me lambda expressions & what they can be used for. I have googled for it & have a rough idea. most of the examples give c# code. How about lambda expressions in plain old C...?

    Read the article

  • What are some examples of MemberBinding linq expressions?

    - by michielvoo
    There are three possibilities, but I can't find examples: System.Linq.Expressions.MemberAssignment System.Linq.Expressions.MemberListBinding System.Linq.Expressions.MemberMemberBinding I want to write some unit tests to see if I can handle them, but I don't know how to write them except for the first one, which seems to be new Foo { Property = "value" } where Property = "value" is an expression of type MemberAssignment. See also this MSDN article.

    Read the article

  • LINQ – SequenceEqual() method

    - by nmarun
    I have been looking at LINQ extension methods and have blogged about what I learned from them in my blog space. Next in line is the SequenceEqual() method. Here’s the description about this method: “Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.” Let’s play with some code: 1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 2: // int[] numbersCopy = numbers; 3: int[] numbersCopy = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 4:  5: Console.WriteLine(numbers.SequenceEqual(numbersCopy)); This gives an output of ‘True’ – basically compares each of the elements in the two arrays and returns true in this case. The result is same even if you uncomment line 2 and comment line 3 (I didn’t need to say that now did I?). So then what happens for custom types? For this, I created a Product class with the following definition: 1: class Product 2: { 3: public int ProductId { get; set; } 4: public string Name { get; set; } 5: public string Category { get; set; } 6: public DateTime MfgDate { get; set; } 7: public Status Status { get; set; } 8: } 9:  10: public enum Status 11: { 12: Active = 1, 13: InActive = 2, 14: OffShelf = 3, 15: } In my calling code, I’m just adding a few product items: 1: private static List<Product> GetProducts() 2: { 3: return new List<Product> 4: { 5: new Product 6: { 7: ProductId = 1, 8: Name = "Laptop", 9: Category = "Computer", 10: MfgDate = new DateTime(2003, 4, 3), 11: Status = Status.Active, 12: }, 13: new Product 14: { 15: ProductId = 2, 16: Name = "Compact Disc", 17: Category = "Water Sport", 18: MfgDate = new DateTime(2009, 12, 3), 19: Status = Status.InActive, 20: }, 21: new Product 22: { 23: ProductId = 3, 24: Name = "Floppy", 25: Category = "Computer", 26: MfgDate = new DateTime(1993, 3, 7), 27: Status = Status.OffShelf, 28: }, 29: }; 30: } Now for the actual check: 1: List<Product> products1 = GetProducts(); 2: List<Product> products2 = GetProducts(); 3:  4: Console.WriteLine(products1.SequenceEqual(products2)); This one returns ‘False’ and the reason is simple – this one checks for reference equality and the products in the both the lists get different ‘memory addresses’ (sounds like I’m talking in ‘C’). In order to modify this behavior and return a ‘True’ result, we need to modify the Product class as follows: 1: class Product : IEquatable<Product> 2: { 3: public int ProductId { get; set; } 4: public string Name { get; set; } 5: public string Category { get; set; } 6: public DateTime MfgDate { get; set; } 7: public Status Status { get; set; } 8:  9: public override bool Equals(object obj) 10: { 11: return Equals(obj as Product); 12: } 13:  14: public bool Equals(Product other) 15: { 16: //Check whether the compared object is null. 17: if (ReferenceEquals(other, null)) return false; 18:  19: //Check whether the compared object references the same data. 20: if (ReferenceEquals(this, other)) return true; 21:  22: //Check whether the products' properties are equal. 23: return ProductId.Equals(other.ProductId) 24: && Name.Equals(other.Name) 25: && Category.Equals(other.Category) 26: && MfgDate.Equals(other.MfgDate) 27: && Status.Equals(other.Status); 28: } 29:  30: // If Equals() returns true for a pair of objects 31: // then GetHashCode() must return the same value for these objects. 32: // read why in the following articles: 33: // http://geekswithblogs.net/akraus1/archive/2010/02/28/138234.aspx 34: // http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c 35: public override int GetHashCode() 36: { 37: //Get hash code for the ProductId field. 38: int hashProductId = ProductId.GetHashCode(); 39:  40: //Get hash code for the Name field if it is not null. 41: int hashName = Name == null ? 0 : Name.GetHashCode(); 42:  43: //Get hash code for the ProductId field. 44: int hashCategory = Category.GetHashCode(); 45:  46: //Get hash code for the ProductId field. 47: int hashMfgDate = MfgDate.GetHashCode(); 48:  49: //Get hash code for the ProductId field. 50: int hashStatus = Status.GetHashCode(); 51: //Calculate the hash code for the product. 52: return hashProductId ^ hashName ^ hashCategory & hashMfgDate & hashStatus; 53: } 54:  55: public static bool operator ==(Product a, Product b) 56: { 57: // Enable a == b for null references to return the right value 58: if (ReferenceEquals(a, b)) 59: { 60: return true; 61: } 62: // If one is null and the other not. Remember a==null will lead to Stackoverflow! 63: if (ReferenceEquals(a, null)) 64: { 65: return false; 66: } 67: return a.Equals((object)b); 68: } 69:  70: public static bool operator !=(Product a, Product b) 71: { 72: return !(a == b); 73: } 74: } Now THAT kinda looks overwhelming. But lets take one simple step at a time. Ok first thing you’ve noticed is that the class implements IEquatable<Product> interface – the key step towards achieving our goal. This interface provides us with an ‘Equals’ method to perform the test for equality with another Product object, in this case. This method is called in the following situations: when you do a ProductInstance.Equals(AnotherProductInstance) and when you perform actions like Contains<T>, IndexOf() or Remove() on your collection Coming to the Equals method defined line 14 onwards. The two ‘if’ blocks check for null and referential equality using the ReferenceEquals() method defined in the Object class. Line 23 is where I’m doing the actual check on the properties of the Product instances. This is what returns the ‘True’ for us when we run the application. I have also overridden the Object.Equals() method which calls the Equals() method of the interface. One thing to remember is that anytime you override the Equals() method, its’ a good practice to override the GetHashCode() method and overload the ‘==’ and the ‘!=’ operators. For detailed information on this, please read this and this. Since we’ve overloaded the operators as well, we get ‘True’ when we do actions like: 1: Console.WriteLine(products1.Contains(products2[0])); 2: Console.WriteLine(products1[0] == products2[0]); This completes the full circle on the SequenceEqual() method. See the code used in the article here.

    Read the article

  • Why does Linq to Entity Sum return null when the list is empty?

    - by Hannele
    There are quite a few questions on Stack Overflow about the Linq to Entity / Linq to SQL Sum extension method, about how it returns null when the result set is empty: 1, 2, 3, 4, 5, 6, 7, and many more, as well as a blog post discussing the issue here. Now, I could go a flag these as duplicates, but I feel it is still an inconsistency in the Linq implementation. I am assuming at this point that it is not a bug, but is more or less working as designed. I understand that there are workarounds (for example, casting the field to a nullable type, so you can coalesce with ??), and I also understand that for the underlying SQL, a NULL result is expected for an empty list. But because the result of the Sum extension for nullable types is also not nullable, why would the Linq to SQL / Linq to Entity Sum have been designed to behave this way?

    Read the article

  • Why does Linq to Entity Sum return null when the result set is empty?

    - by Hannele
    There are quite a few questions on Stack Overflow about the Linq to Entity / Linq to SQL Sum extension method, about how it returns null when the result set is empty: 1, 2, 3, 4, 5, 6, 7, and many more, as well as a blog post discussing the issue here. I feel it is an inconsistency in the Linq implementation. I am assuming at this point that it is not a bug, but is more or less working as designed. I understand that there are workarounds (for example, casting the field to a nullable type, so you can coalesce with ??), and I also understand that for the underlying SQL, a NULL result is expected for an empty result set. But because the result of the Sum extension for non-nullable types is also non-nullable, why does the Linq to SQL / Linq to Entity Sum behave this way?

    Read the article

  • Windows: File copy/move with filename regular expressions?

    - by Ian Boyd
    i basically want to run: C:\>xcopy [0-9]{13}\.(gif|jpg|png) s:\TargetFolder /s i know xcopy doesn't support regular-express filename searches. i can't find out how to find out if PowerShell has a Cmdlet to copy files; and if it does, how to find out if it supports regular expression filename matching. Can anyone think of a way to perform a recursive file copy/move with regex filename matching?

    Read the article

  • How to eager load sibling data using LINQ to SQL?

    - by Scott
    The goal is to issue the fewest queries to SQL Server using LINQ to SQL without using anonymous types. The return type for the method will need to be IList<Child1>. The relationships are as follows: Parent Child1 Child2 Grandchild1 Parent Child1 is a one-to-many relationship Child1 Grandchild1 is a one-to-n relationship (where n is zero to infinity) Parent Child2 is a one-to-n relationship (where n is zero to infinity) I am able to eager load the Parent, Child1 and Grandchild1 data resulting in one query to SQL Server. This query with load options eager loads all of the data, except the sibling data (Child2): DataLoadOptions loadOptions = new DataLoadOptions(); loadOptions.LoadWith<Child1>(o => o.GrandChild1List); loadOptions.LoadWith<Child1>(o => o.Parent); dataContext.LoadOptions = loadOptions; IQueryable<Child1> children = from child in dataContext.Child1 select child; I need to load the sibling data as well. One approach I have tried is splitting the query into two LINQ to SQL queries and merging the result sets together (not pretty), however upon accessing the sibling data it is lazy loaded anyway. Adding the sibling load option will issue a query to SQL Server for each Grandchild1 and Child2 record (which is exactly what I am trying to avoid): DataLoadOptions loadOptions = new DataLoadOptions(); loadOptions.LoadWith<Child1>(o => o.GrandChild1List); loadOptions.LoadWith<Child1>(o => o.Parent); loadOptions.LoadWith<Parent>(o => o.Child2List); dataContext.LoadOptions = loadOptions; IQueryable<Child1> children = from child in dataContext.Child1 select child; exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0] WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=1 exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0] WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=2 exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0] WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=3 exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0] WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=4 I've also written LINQ to SQL queries to join in all of the data in hopes that it would eager load the data, however when the LINQ to SQL EntitySet of Child2 or Grandchild1 are accessed it lazy loads the data. The reason for returning the IList<Child1> is to hydrate business objects. My thoughts are I am either: Approaching this problem the wrong way. Have the option of calling a stored procedure? My organization should not be using LINQ to SQL as an ORM? Any help is greatly appreciated. Thank you, -Scott

    Read the article

  • Inspiring problems to show off the importance of regular expressions?

    - by ragu.pattabi
    I am planning to give a presentation/demonstration on regular expressions at work to encourage young developers to add this powerful and important tool in their toolbox. Just teaching syntax doesn't cut it. I often see people say nice. After the presentation, they get on with their programming lives without ever thinking of using it mostly. I am raking my grey matter to come up with some solid examples, not just problems that matches 'cat' and 'cut'. I missed to note down the occasions of my regex enlightenments to use here. :^( Do you have some inspiring problems to share that could be solved with regex?

    Read the article

  • Can non-IT people learn and take advantage of regular expressions? [closed]

    - by user1598390
    Often times, not-IT people has to deal with massive text data, clean it, filter it, modify it. Often times normal office tools like Excel lack the tools to make complex search and replace operations on text. Could this people benefit from regexps ? Can regexp be taught to them ? Are regular expressions the exclusive domain of programmers and unix/linux technicians ? Can they be learned by non-IT people, given regexps are not a programming language? Is this a valid or achievable goal to make some users regexp-literate through appopriate training ? Have you have any experiences on this issue? and if so, have it been successful ?

    Read the article

  • Regular Expressions Cookbook Code Samples

    - by Jan Goyvaerts
    %COOKBOOKFRAME% One of the common criticisms against the first edition was that we didn’t have the regular expressions and code samples available for download. Since our book only has very short code snippets rather than complete programs, we (the authors) did not have these available as separate files either. But for the second edition we’re trying to do better. You can now download the code samples from the 2nd edition of Regular Expressions Cookbook. This HTML file contains all the blocks with regular expressions and source code from the book, along with the titles of the chapters, recipes, and sections that they are found in. If you have purchased the book, you can use this file to easily copy and paste the regular expressions and source code snippets. Even if you purchased the ebook, you may prefer to use this file. The regexes in the ebook are formatted with line breaks and gray dots for spaces to make them easier to read in print. The HTML file does not use such formatting, so you can copy and paste them directly. This means that some very regexes will run beyond the edge of your browser window.

    Read the article

  • Linq PredicateBuilder with conditional AND, OR and NOT filters.

    - by richeym
    We have a project using LINQ to SQL, for which I need to rewrite a couple of search pages to allow the client to select whether they wish to perform an and or an or search. I though about redoing the LINQ queries using PredicateBuilder and have got this working pretty well I think. I effectively have a class containing my predicates, e.g.: internal static Expression<Func<Job, bool>> Description(string term) { return p => p.Description.Contains(term); } To perform the search i'm doing this (some code omitted for brevity): public Expression<Func<Job, bool>> ToLinqExpression() { var predicates = new List<Expression<Func<Job, bool>>>(); // build up predicates here if (SearchType == SearchType.And) { query = PredicateBuilder.True<Job>(); } else { query = PredicateBuilder.False<Job>(); } foreach (var predicate in predicates) { if (SearchType == SearchType.And) { query = query.And(predicate); } else { query = query.Or(predicate); } } return query; } While i'm reasonably happy with this, I have two concerns: The if/else blocks that evaluate a SearchType property feel like they could be a potential code smell. The client is now insisting on being able to perform 'and not' / 'or not' searches. To address point 2, I think I could do this by simply rewriting my expressions, e.g.: internal static Expression<Func<Job, bool>> Description(string term, bool invert) { if (invert) { return p => !p.Description.Contains(term); } else { return p => p.Description.Contains(term); } } However this feels like a bit of a kludge, which usually means there's a better solution out there. Can anyone recommend how this could be improved? I'm aware of dynamic LINQ, but I don't really want to lose LINQ's strong typing.

    Read the article

  • How do I use Linq-to-sql to iterate db records?

    - by Seth Spearman
    I asked on SO a few days ago what was the simplest quickest way to build a wrapper around a recently completed database. I took the advice and used sqlmetal to build linq classes around my database design. Now I am having two problems. One, I don't know LINQ. And, two, I have been shocked to realize how hard it is to learn. I have a book on LINQ (Linq In Action by Manning) and it has helped some but at the end of the day it is going to take me a couple of weeks to get traction and I need to make some progress on my project today. So, I am looking for some help getting started. Click HERE To see my simple database schema. Click HERE to see the vb class that was generated for the schema. My needs are simple. I have a console app. The main table is the SupplyModel table. Most of the other tables are child tables of the SupplyModel table. I want to iterate through each of Supply Model records. I want to grab the data for a supply model and then DoStuff with the data. And I also need to iterate through the child records, for each supply model, for example the NumberedInventories and DoStuff with that as well. I need help doing this in VB rather than C# if possible. I am not looking for the whole solution...if you can supply a couple of code-snippets to get me on my way that would be great. Thanks for your help. Seth

    Read the article

  • Entity Framework LINQ Query using Custom C# Class Method - Once yes, once no - because executing on the client or in SQL?

    - by BrooklynDev
    I have two Entity Framework 4 Linq queries I wrote that make use of a custom class method, one works and one does not: The custom method is: public static DateTime GetLastReadToDate(string fbaUsername, Discussion discussion) { return (discussion.DiscussionUserReads.Where(dur => dur.User.aspnet_User.UserName == fbaUsername).FirstOrDefault() ?? new DiscussionUserRead { ReadToDate = DateTime.Now.AddYears(-99) }).ReadToDate; } The linq query that works calls a from after a from, the equivalent of SelectMany(): from g in oc.Users.Where(u => u.aspnet_User.UserName == fbaUsername).First().Groups from d in g.Discussions select new { UnReadPostCount = d.Posts.Where(p => p.CreatedDate > DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count() }; The query that does not work is more like a regular select: from d in oc.Discussions where d.Group.Name == "Student" select new { UnReadPostCount = d.Posts.Where(p => p.CreatedDate > DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count(), }; The error I get is: LINQ to Entities does not recognize the method 'System.DateTime GetLastReadToDate(System.String, Discussion)' method, and this method cannot be translated into a store expression. My question is, why am I able to use my custom GetLastReadToDate() method in the first query and not the second? I suppose this has something to do with what gets executed on the db server and what gets executed on the client? These queries seem to use the GetLastReadToDate() method so similarly though, I'm wondering why would work for the first and not the second, and most importantly if there's a way to factor common query syntax like what's in the GetLastReadToDate() method into a separate location to be reused in several different places LINQ queries. Please note all these queries are sharing the same object context.

    Read the article

  • Use LINQ, to Sort and Filter items in a List<ReturnItem> collection, based on the values within a Li

    - by Daniel McPherson
    This is tricky to explain. We have a DataTable that contains a user configurable selection of columns, which are not known at compile time. Every column in the DataTable is of type String. We need to convert this DataTable into a strongly typed Collection of "ReturnItem" objects so that we can then sort and filter using LINQ for use in our application. We have made some progress as follows: We started with the basic DataTable. We then process the DataTable, creating a new "ReturnItem" object for each row This "ReturnItem" object has just two properties: ID ( string ) and Columns( List(object) ). The properties collection contains one entry for each column, representing a single DataRow. Each property is made Strongly Typed (int, string, datetime, etc). For example it would add a new "DateTime" object to the "ReturnItem" Columns List containing the value of the "Created" Datatable Column. The result is a List(ReturnItem) that we would then like to be able to Sort and Filter using LINQ based on the value in one of the properties, for example, sort on "Created" date. We have been using the LINQ Dynamic Query Library, which gets us so far, but it doesn't look like the way forward because we are using it over a List Collection of objects. Basically, my question boils down to: How can I use LINQ, to Sort and Filter items in a List(ReturnItem) collection, based on the values within a List(object) property which is part of the ReturnItem class?

    Read the article

  • LINQ to SQL exception: System.OutOfMemoryException

    - by Adam
    Not sure why I keep getting an OutOfMemory exception. I'm using ASP.NET MVC with LINQ to SQL. Here's some of the stack trace: [OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.] System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IntPtr method) +0 System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType) +7652553 System.Data.Linq.SqlClient.ObjectReaderCompiler.Compile(SqlExpression expression, Type elementType) +442 System.Data.Linq.SqlClient.SqlProvider.GetReaderFactory(SqlNode node, Type elemType) +100 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +253 System.Data.Linq.Table1.System.Linq.IQueryProvider.Execute(Expression expression) +49 System.Linq.Queryable.Single(IQueryable1 source, Expression`1 predicate) +301 WorkGrabber.Web.Models.WorkGrabberDataContext.GetJob(Int32 id) +233 WorkGrabber.Web.Controllers.BidsController.New(Int32 jobId) +19

    Read the article

  • What's the next big thing after LINQ?

    - by Leniel Macaferi
    I started using LINQ (Language Integrated Query) when it was still in beta, more specifically Microsoft .NET LINQ Preview (May 2006). Almost 4 years have passed and here we are using LINQ in a lot of projects for the most diverse tasks. I even wrote my final college project based on LINQ. You see how I like it. LINQ and more recently PLINQ (Parallel LINQ) give our jobs a great boost when it comes to more programming power and less lines of code leading us to more expressive and readable code. I keep thinking what could be the next big language improvement for C# after LINQ. I know there are some promissing language features coming as Code Contracts, etc, but nothing having the impact that LINQ had. What do you think could be the next big thing?

    Read the article

  • LINQ – TakeWhile and SkipWhile methods

    - by nmarun
    I happened to read about these methods on Vikram's blog and tried testing it. Somehow when I saw the output, things did not seem to add up right. I’m writing this blog to show the actual workings of these methods. Let’s take the same example as showing in Vikram’s blog and I’ll build around it. 1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 2:  3: foreach(var number in numbers.TakeWhile(n => n < 7)) 4: { 5: Console.WriteLine(number); 6: } Now, the way I (incorrectly) read the upper bound condition in the foreach loop was: ‘Give me all numbers that pass the condition of n<7’. So I was expecting the answer to be: 5, 4, 1, 3, 2, 0. But when I run the application, I see only: 5, 4, 1,3. Turns out I was wrong (happens at least once a day). The documentation on the method says ‘Returns elements from a sequence as long as a specified condition is true. To show in code, my interpretation was the below code’: 1: foreach (var number in numbers) 2: { 3: if (number < 7) 4: { 5: Console.WriteLine(number); 6: } 7: } But the actual implementation is: 1: foreach(var number in numbers) 2: { 3: if(number < 7) 4: { 5: Console.WriteLine(number); 6: break; 7: } 8: } So there it is, another situation where one simple word makes a difference of a whole world. The SkipWhile method has been implemented in a similar way – ‘Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements’ and not ‘Bypasses elements in a sequence where a specified condition is true and then returns the remaining elements’. (Subtle.. very very subtle). It’s feels strange saying this, but hope very few require to read this article to understand these methods.

    Read the article

  • LINQ for SQL Developers and DBA’s

    - by AtulThakor
    Firstly I’d just like to thank the guys who organise the SQL Server User Group (Martin/Tony/Chris) and for giving me the opportunity to speak at the recent event. Sorry about the slides taking so long but here they are along with some extra information. Firstly the demo’s were all done using LINQPad 4.0 which can be downloaded here: http://www.linqpad.net/ There are 2 versions 3.5/4.0 With 3.5 you should be able to replicate the problem I showed where a query using a parameter which is X characters long would create a different execution plan to a query which uses a parameter which is Y characters long, otherwise I would just use 4.0 The sample database used is AdventureWorksLT2008 which can be downloaded from here: http://msftdbprodsamples.codeplex.com/releases/view/37109 The scripts have been named so that you can select the appropriate way to run them i.e.: C# expression / C#statement, each script can be run individually be highlighting the query and clicking the play symbol or hitting F5. Scripts and Slides: http://sqlblogcasts.com/blogs/atulthakor/An%20Introduction%20to%20LINQ.zip Please don't hesitate in sending any questions via email/twitter, I’ll try my best to answer your questions! Thanks, Atul

    Read the article

  • Grouping data in LINQ with the help of group keyword

    - by vik20000in
    While working with any kind of advanced query grouping is a very important factor. Grouping helps in executing special function like sum, max average etc to be performed on certain groups of data inside the date result set. Grouping is done with the help of the Group method. Below is an example of the basic group functionality.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };         var numberGroups =         from num in numbers         group num by num % 5 into numGroup         select new { Remainder = numGroup.Key, Numbers = numGroup };  In the above example we have grouped the values based on the reminder left over when divided by 5. First we are grouping the values based on the reminder when divided by 5 into the numgroup variable.  numGroup.Key gives the value of the key on which the grouping has been applied. And the numGroup itself contains all the records that are contained in that group. Below is another example to explain the same. string[] words = { "blueberry", "abacus", "banana", "apple", "cheese" };         var wordGroups =         from num in words         group num by num[0] into grp         select new { FirstLetter = grp.Key, Words = grp }; In the above example we are grouping the value with the first character of the string (num[0]). Just like the order operator the group by clause also allows us to write our own logic for the Equal comparison (That means we can group Item by ignoring case also by writing out own implementation). For this we need to pass an object that implements the IEqualityComparer<string> interface. Below is an example. public class AnagramEqualityComparer : IEqualityComparer<string> {     public bool Equals(string x, string y) {         return getCanonicalString(x) == getCanonicalString(y);     }      public int GetHashCode(string obj) {         return getCanonicalString(obj).GetHashCode();     }         private string getCanonicalString(string word) {         char[] wordChars = word.ToCharArray();         Array.Sort<char>(wordChars);         return new string(wordChars);     } }  string[] anagrams = {"from   ", " salt", " earn", "  last   ", " near "}; var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer()); Vikram  

    Read the article

  • Enhancing performance in Entity Framework applications by precompiling LINQ to Entities queries

    - by nikolaosk
    This is going to be the tenth post of a series of posts regarding ASP.Net and the Entity Framework and how we can use Entity Framework to access our datastore. You can find the first one here , the second one here , the third one here , the fourth one here , the fifth one here ,the sixth one here ,the seventh one here ,the eighth one here and the ninth one here . I have a post regarding ASP.Net and EntityDataSource . You can read it here .I have 3 more posts on Profiling Entity Framework applications...(read more)

    Read the article

  • LINQ: Enhancing Distinct With The SelectorEqualityComparer

    - by Paulo Morgado
    On my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements. Using the predicate, greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don’t want to provide a comparison method but just to extract the comaprison key for the elements. So, I developed a SelectorEqualityComparer that takes a method that extracts the key value for each element. Something like this: public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource> where Tkey : IEquatable<Tkey> { private Func<TSource, Tkey> selector; public SelectorEqualityComparer(Func<TSource, Tkey> selector) : base() { this.selector = selector; } public override bool Equals(TSource x, TSource y) { Tkey xKey = this.GetKey(x); Tkey yKey = this.GetKey(y); if (xKey != null) { return ((yKey != null) && xKey.Equals(yKey)); } return (yKey == null); } public override int GetHashCode(TSource obj) { Tkey key = this.GetKey(obj); return (key == null) ? 0 : key.GetHashCode(); } public override bool Equals(object obj) { SelectorEqualityComparer<TSource, Tkey> comparer = obj as SelectorEqualityComparer<TSource, Tkey>; return (comparer != null); } public override int GetHashCode() { return base.GetType().Name.GetHashCode(); } private Tkey GetKey(TSource obj) { return (obj == null) ? (Tkey)(object)null : this.selector(obj); } } Now I can write code like this: .Distinct(new SelectorEqualityComparer<Source, Key>(x => x.Field)) And, for improved readability, conciseness and expressiveness and support for anonymous types the corresponding Distinct extension method: public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IEquatable<TKey> { return source.Distinct(new SelectorEqualityComparer<TSource, TKey>(selector)); } And the query is now written like this: .Distinct(x => x.Field) For most usages, it’s simpler than using a predicate.

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >