Search Results

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

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

  • Complex LINQ paging algorithm

    - by sharepointmonkey
    We have a list of projects that may or may not have a collection of subprojects. Our report needs to contain all the projects except those that are the parent project of a subproject. I need to page this into pages of, say, 25 rows. But if subprojects appear on that page then ALL the subprojects of that project must appear on the same page. So more than 25 items may appear if necessary. I've got as far as var pagedProjects = db.Projects.Where(x => !x.SubProjects.Any()).Skip( (pageNo -1) * pageSize).Take(pageSize); Obviously, this fails the second part of the requirements. As a further pain in the arse, I need to have a pager control on the report. So I'll need to be able to calculate the total number of pages. I could loop through the whole table of projects but the performance will suffer. Can anybody come up with a paged solution? EDIT - I should probably mention that SubProjects joins back onto Projects via a selfreferencing foreign key so the whole lot comes back as an IQueryable<Project>.

    Read the article

  • help with exception handling in linq

    - by stackoverflowuser
    I have the following code to retrieve customer name, total (orders ), sum (order details) for reach customer in Northwind database. The problem with below code is that it raises an exception since a few customers dont have any entry in orders table. I know using the query syntax (join) the exception can be avoided. I want to know if the same can be handled with the extension method syntax. CustomerOrderDataContext db = new CustomerOrderDataContext(); var customerOrders = db.Customers.Select(c => new { CompanyName = c.CompanyName, TotalOrders = c.Orders.Count(), TotalQuantity = c.Orders.SelectMany(o => o.Order_Details).Sum(o=>o.Quantity) });

    Read the article

  • Difference in linq-to-sql query performance using GenericRespositry

    - by Neil
    Given i have a class like so in my Data Layer public class GenericRepository<TEntity> where TEntity : class { [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)] public IQueryable<TEntity> SelectAll() { return DataContext.GetTable<TEntity>(); } } I would be able to query a table in my database like so from a higher layer using (GenericRepositry<MyTable> mytable = new GenericRepositry<MyTable>()) { var myresult = from m in mytable.SelectAll() where m.IsActive select m; } is this considerably slower than using the usual code in my Data Layer using (MyDataContext ctx = new MyDataContext()) { var myresult = from m in ctx.MyTable where m.IsActive select m; } Eliminating the need to write simple single table selects in the Data layer saves a lot of time, but will i regret it?

    Read the article

  • LinQ XML mapping to a generic type

    - by Manuel Navarro
    I´m trying to use an external XML file to map the output from a stored procedure into an instance of a class. The problem is that my class is of a generic type: public class MyValue<T> { public T Value { get; set; } } Searching through a lot of blogs an articles I've managed to get this: <?xml version="1.0" encoding="utf-8" ?> <Database Name="" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="MyValue" Member="MyNamespace.MyValue`1" > <Type Name="MyNamespace.MyValue`1"> <Column Name="Category" Member="Value" DbType="VarChar(100)" /> </Type> </Table> <Function Method="GetResourceCategories" Name="myprefix_GetResourceCategories" > <ElementType Name="MyNamespace.MyValue`1"/> </Function> </Database> The MyNamespace.MyValue`1 trick works fine, and the class is recognized. I expect four rows from the stored procedure, and I'm getting four MyValue<string> instances, but the big problem is that the property Value for the all four instances is null. The property is not getting mapped and I don't really get why. Maybe worth noting that the property Value is generic, and that when the mapping is done using attributes it works perfect. Anyone have a clue? BTW the method GetResourceCategories: public ISingleResult<MyValue<string>> GetResourceCategories() { IExecuteResult result = this.ExecuteMethodCall( this, (MethodInfo)MethodInfo.GetCurrentMethod()); return (ISingleResult<MyValue<string>>)result.ReturnValue; }

    Read the article

  • Linq with a long where clause

    - by Jeremy Roberts
    Is there a better way to do this? I tried to loop over the partsToChange collection and build up the where clause, but it ANDs them together instead of ORing them. I also don't really want to explicitly do the equality on each item in the partsToChange list. var partsToChange = new Dictionary<string, string> { {"0039", "Vendor A"}, {"0051", "Vendor B"}, {"0061", "Vendor C"}, {"0080", "Vendor D"}, {"0081", "Vendor D"}, {"0086", "Vendor D"}, {"0089", "Vendor E"}, {"0091", "Vendor F"}, {"0163", "Vendor E"}, {"0426", "Vendor B"}, {"1197", "Vendor B"} }; var items = new List<MaterialVendor>(); foreach (var x in partsToChange) { var newItems = ( from m in MaterialVendor where m.Material.PartNumber == x.Key && m.Manufacturer.Name.Contains(x.Value) select m ).ToList(); items.AddRange(newItems); } Additional info: I am working in LINQPad.

    Read the article

  • c# linq to sql join problem

    - by b0x0rz
    i am trying to do using (UserManagementDataContext context = new UserManagementDataContext()) { var users = from u in context.Users where u.UserEMailAdresses.EMailAddress == "[email protected]" select u; return users.Count(); } however, when i get to: using (UserManagementDataContext context = new UserManagementDataContext()) { var users = from u in context.Users where u.UserEMailAdresses. i do not get offered the EMailAddress name, but rather some neutral default-looking list of options in intelisense. what am i doing wrong? table Users ID bigint NameTitle nvarchar(64) NameFirst nvarchar(64) NameMiddle nvarchar(64) NameLast nvarchar(64) NameSuffix nvarchar(64) Status bigint IsActive bit table UserEMailAddresses ID bigint UserID bigint EMailAddress nvarchar(256) IsPrimary bit IsActive bit obviously, 1 user can have many addresses and so Users.ID and UserEMailAddresses.UserID have a relationship between them: 1 to MANY.

    Read the article

  • Exception handling in Linq to SQL for customers without orders

    - by stackoverflowuser
    I have the following code to retrieve customer name, total (orders ), sum (order details) for reach customer in Northwind database. The problem with below code is that it raises an exception since a few customers dont have any entry in orders table. I know using the query syntax (join) the exception can be avoided. I want to know if the same can be handled with the extension method syntax. var customerOrders = db.Customers .Select(c => new { CompanyName = c.CompanyName, TotalOrders = c.Orders.Count(), TotalQuantity = c.Orders .SelectMany(o => o.Order_Details).Sum(o=>o.Quantity) });

    Read the article

  • Linq qurery with multiple where's

    - by Dan
    I am trying the to query my Status Update repository using the following var result = (from s in _dataContext.StatusUpdates where s.Username == "friend1" && s.Username == "friend2" etc... select s).ToList(); Insead of using s.Username == "friendN" continously is there anyway I can pass a list or array or something like that rather that specifying each one, or can i use a foreach loop in the middle of the query. Thanks

    Read the article

  • XDocument + IEnumerable is causing out of memory exception in System.Xml.Linq.dll

    - by Manatherin
    Basically I have a program which, when it starts loads a list of files (as FileInfo) and for each file in the list it loads a XML document (as XDocument). The program then reads data out of it into a container class (storing as IEnumerables), at which point the XDocument goes out of scope. The program then exports the data from the container class to a database. After the export the container class goes out of scope, however, the garbage collector isn't clearing up the container class which, because its storing as IEnumerable, seems to lead to the XDocument staying in memory (Not sure if this is the reason but the task manager is showing the memory from the XDocument isn't being freed). As the program is looping through multiple files eventually the program is throwing a out of memory exception. To mitigate this ive ended up using System.GC.Collect(); to force the garbage collector to run after the container goes out of scope. this is working but my questions are: Is this the right thing to do? (Forcing the garbage collector to run seems a bit odd) Is there a better way to make sure the XDocument memory is being disposed? Could there be a different reason, other than the IEnumerable, that the document memory isnt being freed? Thanks. Edit: Code Samples: Container Class: public IEnumerable<CustomClassOne> CustomClassOne { get; set; } public IEnumerable<CustomClassTwo> CustomClassTwo { get; set; } public IEnumerable<CustomClassThree> CustomClassThree { get; set; } ... public IEnumerable<CustomClassNine> CustomClassNine { get; set; }</code></pre> Custom Class: public long VariableOne { get; set; } public int VariableTwo { get; set; } public DateTime VariableThree { get; set; } ... Anyway that's the basic structures really. The Custom Classes are populated through the container class from the XML document. The filled structures themselves use very little memory. A container class is filled from one XML document, goes out of scope, the next document is then loaded e.g. public static void ExportAll(IEnumerable<FileInfo> files) { foreach (FileInfo file in files) { ExportFile(file); //Temporary to clear memory System.GC.Collect(); } } private static void ExportFile(FileInfo file) { ContainerClass containerClass = Reader.ReadXMLDocument(file); ExportContainerClass(containerClass); //Export simply dumps the data from the container class into a database //Container Class (and any passed container classes) goes out of scope at end of export } public static ContainerClass ReadXMLDocument(FileInfo fileToRead) { XDocument document = GetXDocument(fileToRead); var containerClass = new ContainerClass(); //ForEach customClass in containerClass //Read all data for customClass from XDocument return containerClass; } Forgot to mention this bit (not sure if its relevent), the files can be compressed as .gz so I have the GetXDocument() method to load it private static XDocument GetXDocument(FileInfo fileToRead) { XDocument document; using (FileStream fileStream = new FileStream(fileToRead.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (String.Compare(fileToRead.Extension, ".gz", true) == 0) { using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress)) { document = XDocument.Load(zipStream); } } else { document = XDocument.Load(fileStream); } return document; } } Hope this is enough information. Thanks Edit: The System.GC.Collect() is not working 100% of the time, sometimes the program seems to retain the XDocument, anyone have any idea why this might be?

    Read the article

  • LINQ : How to query how to sort result by most similarity/equality

    - by aNui
    I want to do a search for Music instruments which has its informations Name, Category and Origin as I asked in my post. But now I want to sort/group the result by similarity/equality to the keyword such as. If I have the list { Harp, Piano, Drum, Guitar, Guitarrón } and if I queried "p" the result should be { Piano, Harp } but it shows Harp first because of the list's sequence and if I add {Grand Piano} to the list and query "piano" the result shoud be like { Piano, Grand Piano } here's my code static IEnumerable<MInstrument> InstrumentsSearch(IEnumerable<MInstrument> InstrumentsList, string query, MInstrument.Category[] SelectedCategories, MInstrument.Origin[] SelectedOrigins) { var result = InstrumentsList .Where(item => SelectedCategories.Contains(item.category)) .Where(item => SelectedOrigins.Contains(item.origin)) .Where(item => { if ( (" " + item.Name.ToLower()).Contains(" " + query.ToLower()) || item.Name.IndexOf(query) != -1 ) { return true; } return false; } ) .Take(30); return result.ToList<MInstrument>(); } Or the result may be like my old self-invented algorithm that I called "by order of occurence", that is just OK to me. Is there any way to do that, please tell me. Thanks in advance.

    Read the article

  • How to retrieve indentity column vaule after insert using LINQ

    - by Hobey
    Could any of you please show me how to complete the following tasks? // Prepare object to be saved // Note that MasterTable has MasterTableId as a Primary Key and it is an indentity column MasterTable masterTable = new MasterTable(); masterTable.Column1 = "Column 1 Value"; masterTable.Column2 = 111; // Instantiate DataContext DataContext myDataContext = new DataContext("<<ConnectionStrin>>"); // Save the record myDataContext.MasterTables.InsertOnSubmit(masterTable); myDataContext.SubmitChanges(); // ?QUESTION? // Now I need to retrieve the value of MasterTableId for the record just inserted above. Kind Regards

    Read the article

  • Copy Rows in a One to Many with LINQ (2 SQL)

    - by Refracted Paladin
    I have a table that stores a bunch of diagnosis for a single plan. When the users create a new plan I need to copy over all existing diagnosis's as well. I had thought to try the below but this is obviously not correct. I am guessing that I will need to loop through my oldDiagnosis part, but how? Thanks! My Attempt so far... public static void CopyPlanDiagnosis(int newPlanID, int oldPlanID) { using (var context = McpDataContext.Create()) { var oldDiagnosis = from planDiagnosi in context.tblPlanDiagnosis where planDiagnosi.PlanID == oldPlanID select planDiagnosi; var newDiagnosis = new tblPlanDiagnosi { PlanID = newPlanID, DiagnosisCueID = oldDiagnosis.DiagnosisCueID, DiagnosisOther = oldDiagnosis.DiagnosisOther, AdditionalInfo = oldDiagnosis.AdditionalInfo, rowguid = Guid.NewGuid() }; context.tblPlanDiagnosis.InsertOnSubmit(newDiagnosis); context.SubmitChanges(); } }

    Read the article

  • Copy Rows in a One to Many with LINQ to SQL

    - by Refracted Paladin
    I have a table that stores a bunch of diagnosis for a single plan. When the users create a new plan I need to copy over all existing diagnosis's as well. I had thought to try the below but this is obviously not correct. I am guessing that I will need to loop through my oldDiagnosis part, but how? Thanks! My Attempt so far... public static void CopyPlanDiagnosis(int newPlanID, int oldPlanID) { using (var context = McpDataContext.Create()) { var oldDiagnosis = from planDiagnosi in context.tblPlanDiagnosis where planDiagnosi.PlanID == oldPlanID select planDiagnosi; var newDiagnosis = new tblPlanDiagnosi { PlanID = newPlanID, DiagnosisCueID = oldDiagnosis.DiagnosisCueID, DiagnosisOther = oldDiagnosis.DiagnosisOther, AdditionalInfo = oldDiagnosis.AdditionalInfo, rowguid = Guid.NewGuid() }; context.tblPlanDiagnosis.InsertOnSubmit(newDiagnosis); context.SubmitChanges(); } }

    Read the article

  • LINQ to XML: suppressing redundant namespace attribute in child nodes

    - by GSerg
    If a node belongs to a namespace, it's children by default belong to the same namespace. So there's no need to provide an xmlns attribute on each child, which is good. However. If I create two nodes like this: Dim parent = <parent xmlns="http://my.namespace.org"/> Dim child = <child xmlns="http://my.namespace.org">value</child> parent.Add(child) Console.WriteLine(parent.ToString) The result is this: <parent xmlns="http://my.namespace.org"> <child xmlns="http://my.namespace.org">value</child> </parent> But, if create them in a less convenient way: Dim parent = <parent xmlns="http://my.namespace.org"/> Dim child As New XElement(XName.Get("child", "http://my.namespace.org")) With {.Value = "value"} parent.Add(child) Console.WriteLine(parent.ToString) The result is more desirable: <parent xmlns="http://my.namespace.org"> <child>value</child> </parent> Obviously, I'd prefer to use the first way because it is so much more intuitive and easy to code. There's also another reason to not use method 2 -- sometimes I need to create nodes with XElement.Parse, parsing a string that contains an xmlns attribute, which produces exactly same results as method 1. So the question is -- how do I get the pretty output of method 2, creating nodes as in method 1? The only option I see is to create a method that would clone given XElement, effectively recreating it according to method 2 pattern, but that seems ugly. I'm looking for a more obvious solution I overlooked for some reason.

    Read the article

  • LINQ and the use of Repeat and Range operator

    - by vik20000in
    LINQ is also very useful when it comes to generation of range or repetition of data.  We can generate a range of data with the help of the range method.     var numbers =         from n in Enumerable.Range(100, 50)         select new {Number = n, OddEven = n % 2 == 1 ? "odd" : "even"}; The above query will generate 50 records where the record will start from 100 till 149. The query also determines if the number is odd or even. But if we want to generate the same number for multiple times then we can use the Repeat method.     var numbers = Enumerable.Repeat(7, 10); The above query will produce a list with 10 items having the value 7. Vikram

    Read the article

  • Sort method versus OrderBy LINQ extension method

    - by nmarun
    I have a class Product with an Id and a Name as properties. There are multiple ways of getting a list of products to display in sorted/ordered fashion, say, by the Name of the product. The two I’m concerned about here are the Sort and the OrderBy extension method through LINQ and the difference between them. 1: public class Product 2: { 3: public int Id { get; set; } 4: public string Name { get; set; } 5: } Below is the list of products that I’ll be using and is defined somewhere in the Program.cs...(read more)

    Read the article

  • 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

  • How can I combine several Expressions into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method. UPDATE So, whilst it appears that there is no way to do this directly in C#3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit?

    Read the article

  • LINQ 2 Entities , howto check DateTime.HasValue within the linq query

    - by Snoop Dogg
    Hi all ... I have this method that is supposed to get the latest messages posted, from the Table (& EntitySet) called ENTRY ///method gets "days" as parameter, used in new TimeSpan(days,0,0,0);!! using (Entities db = new Entities()) { var entries = from ent in db.ENTRY where ent.DATECREATE.Value > DateTime.Today.Subtract(new TimeSpan(days, 0, 0, 0)) select new ForumEntryGridView() { id = ent.id, baslik = ent.header, tarih = ent.entrydate.Value, membername = ent.Member.ToString() }; return entries.ToList<ForumEntryGridView>(); } Here the DATECREATED is Nullable in the database. I cant place "if"s in this query ... any way to check for that? Thx in advance

    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

  • regular expressions: love or hate or alternatives?

    - by yamspog
    While I can see the value and usefulness of regular expressions, I also find that they are extremely complicated and difficult to create and debug. I am often at the point where I find their usefulness is offset by the difficulty in creating expressions. I am a bit astonished by the fact that there is nothing quite like them and that there hasn't been an effort to recreate them use a more verbose or less arcane syntax. so, are regular expressions here to stay? are there alternatives that are gaining traction? do other people just ignore them and write hundreds of lines of string compare functions?

    Read the article

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