Search Results

Search found 6744 results on 270 pages for 'linq to entities'.

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

  • LINQ/LAMBDA filter query by date [on hold]

    - by inquisitive_one
    I'm trying to use LINQ to SQL to retrieve earnings data for a particular date range. Currently the table is set up as follows: Comp Eps Year Quarter IBM .5 2012 2 IBM .65 2012 3 IBM .60 2012 4 IBM .5 2011 2 IBM .7 2013 1 IBM .8 2013 2 Except for Eps, all fields have a data type of string or char. Eps has a data type of double. Here's my code: var myData = myTable .Where(t => t.Comp.Equals("IBM") && Convert.Int32(string.Format("{0}{1}", t.Year, t.Quarter)) <= 20131); I get the following error when I tried that code: Method 'System.String Format(System.String, System.Object, System.Object)' has no supported translation to SQL How can I select all Eps that has a year & quarter less than "20132" using a lambda expression?

    Read the article

  • Using linq to parse file [closed]

    - by Emaan Abdul majeed
    i am working parsing textfile using LINQ but got struc on it,its going outof range exception string[] lines = File.ReadAllLines(input); var t1 = lines .Where(l => !l.StartsWith("#")) .Select(l => l.Split(' ')) .Select(items => String.Format("{0}{1}{2}", items[1].PadRight(32), //items[1].PadRight(16) items[2].PadRight(32), items[3].PadRight(32))); var t2 = t1 .Select(l => l.ToUpper()); foreach (var t in t2) Console.WriteLine(t); and file is about 200 to 500 lines and i want to extract specific information so i need to split that information to different structure so how to do it this..

    Read the article

  • Is there something like LINQ for Java?

    - by Kb
    Started to learn LINQ with C#. Especially LINQ to Objects and LINQ to XML. I really enjoy the power of LINQ. I learned that there is something called JLINQ a Jscript implementation. Also (as Catbert posted) Scala will have LINQ Do you know if LINQ or something similar will be a part of Java 7? Update: Interesting post from 2008 - http://stackoverflow.com/questions/346721/linq-for-java

    Read the article

  • LINQ to Entities question about orderby and null collections.

    - by Chevex
    I am currently developing a forum. I am new to LINQ and EF. In my forum I have a display that shows a list of topics with the most recent topics first. The problem is that "most recent" is relative to the topic's replies. So I don't want to order the list by the topic's posted date, rather I want to order the list by the topic's last reply's posted date. So that topics with newer replies pop back to the top of the list. This is rather simple if I knew that every topic had at least one reply; I would just do this: var topicsQuery = from x in board.Topics orderby x.Replies.Last().PostedDate descending select x; However, in many cases the topic has no replies. In which case I would like to use the topic's posted date instead. Is there a way within my linq query to order by x.PostedDate in the event that the topic has no replies? I'm getting confused by this and any help would be appreciated. With the above query, it breaks on topics with no replies because of the x.Replies.Last() which assumes there are replies. LastOrDefault() doesn't work because I need to access the PostedDate property which also assumes a reply exists. Thanks in advance for any insight.

    Read the article

  • LINQ: Single vs. First

    - by Paulo Morgado
    I’ve witnessed and been involved in several discussions around the correctness or usefulness of the Single method in the LINQ API. The most common argument is that you are querying for the first element on the result set and an exception will be thrown if there’s more than one element. The First method should be used instead, because it doesn’t throw if the result set has more than one item. Although the documentation for Single states that it returns a single, specific element of a sequence of values, it actually returns THE single, specific element of a sequence of ONE value. One you use the Single method in your code you are asserting that your query will result in a scalar result instead of a result set of arbitrary length. On the other hand, the documentation for First states that it returns the first element of a sequence of arbitrary length. Imagine you want to catch a taxi. You go the the taxi line and catch the FIRST one, no matter how many are there. On the other hand, if you go the the parking lot to get your car, you want the SINGLE one specific car that’s yours. If your “query” “returns” more than one car, it’s an exception. Either because it “returned” not only your car or you happen to have more than one car in that parking lot. In either case, you can only drive one car at once and you’ll need to refine your “query”.

    Read the article

  • TakeWhile and SkipWhile method in LINQ

    - by vik20000in
     In my last post I talked about how to use the take and the Skip keyword to filter out the number of records that we are fetching. But there is only problem with the take and skip statement. The problem lies in the dependency where by the number of records to be fetched has to be passed to it. Many a times the number of records to be fetched is also based on the query itself. For example if we want to continue fetching records till a certain condition is met on the record set. Let’s say we want to fetch records from the array of number till we get 7. For this kind of query LINQ has exposed the TakeWhile Method.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };     var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 7);   In the same way we can also use the SkipWhile statement. The skip while statement will skip all the records that do not match certain condition provided. In the example below we are skiping all those number which are not divisible by 3. Remember we could have done this with where clause also, but SkipWhile method can be useful in many other situation and hence the example and the keyword.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };     var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0); Vikram

    Read the article

  • 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

  • Howto use predicates in LINQ to Entities for Entity Framework objects

    - by user274947
    I'm using LINQ to Entities for Entity Framework objects in my Data Access Layer. My goal is to filter as much as I can from the database, without applying filtering logic on in-memory results. For that purpose Business Logic Layer passes a predicate to Data Access Layer. I mean Func<MyEntity, bool> So, if I use this predicate directly, like public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched) { return qry = _Context.MyEntities.Where(x => isMatched(x)); } I'm getting the exception [System.NotSupportedException] --- {"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."} Solution in that question suggests to use AsExpandable() method from LINQKit library. But again, using public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched) { return qry = _Context.MyEntities.AsExpandable().Where(x => isMatched(x)); } I'm getting the exception Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression' Is there way to use predicate in LINQ to Entities query for Entity Framework objects, so that it is correctly transformed it into a SQL statement. Thank you.

    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

  • Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

    - by BritishDeveloper
    How would you rate each of them in terms of: Performance Speed of development Neat, intuitive, maintainable code Flexibility Overall I like my SQL and so have always been a die-hard fan of ADO.NET and stored procedures but I recently had a play with Linq to SQL and was blown away by how quickly I was writing out my DataAccess layer and have decided to spend some time really understanding either Linq to SQL or EF... or neither? I just want to check, that there isn't a great flaw in any of these technologies that would render my research time useless. E.g. performance is terrible, it's cool for simple apps but can only take you so far

    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

  • 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

  • What is the return type for a anonymous linq query select? What is the best way to send this data ba

    - by punkouter
    This is a basic question. I have the basic SL4/RIA project set up and I want to create a new method in the domain service and return some data from it. I am unsure the proper easiest way to do this.. Should I wrap it up in a ToList()? I am unclear how to handle this anonymous type that was create.. what is the easiest way to return this data? public IQueryable<ApplicationLog> GetApplicationLogsGrouped() { var x = from c in ObjectContext.ApplicationLogs let dt = c.LogDate group c by new { y = dt.Value.Year, m = dt.Value.Month, d = dt.Value.Day } into mygroup select new { aaa = mygroup.Key, ProductCount = mygroup.Count() }; return x; // return this.ObjectContext.ApplicationLogs.Where(r => r.ApplicationID < 50); } Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<CapRep4.Web.ApplicationLog>'. An explicit conversion exists (are you missing a cast?) 58 20 CapRep4.Web

    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

  • 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

  • Comparing multiple entity properties against list of entities

    - by roosteronacid
    Consider this snippet of code: var iList = new List<Entities.Ingredient> { new Entities.Ingredient { Name = "tomato", Amount = 2.0 }, new Entities.Ingredient { Name = "cheese", Amount = 100.0 } }; var matches = new DataContext().Ingredients.Where(i => Comparer(i, iList)); private Boolean Comparer(Entities.Ingredient i, List<Entities.Ingredient> iList) { foreach (var i in iList) { if (i.Name == iList.Name && i.Amount >= iList.Amount) return true; } return false; } Is there a more efficient way of doing this? Preferably without being too verbose; from x in y select z... If thats at all possible.

    Read the article

  • "Select NOT IN" clause in Linq to Entities

    - by lnetanel
    Hi, Is there a way to use the "NOT IN (select XXX...)" clause in Linq to Entities? All the questions I found were regarding a list of objects (IN (1,2,3)) but I want to generate a query with the following syntax: "select * from table1 where field1 not in(select subfield from subtable)" Be aware that this is Linq to Entities and not Linq to Sql... Is it possible? Thanks!

    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

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