Search Results

Search found 25852 results on 1035 pages for 'linq query syntax'.

Page 9/1035 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • linq - how to sort a list

    - by Billy Logan
    Hello everyone, I have a linq query that populates a list of designers. since i am using the filters below my sorting is not functioning properly. My question is with the given code below how can i best sort this List after the fact or sort while querying? I have tried to sort the list after the fact using the following script but i receive a compiler error: List<TBLDESIGNER> designers = new List<TBLDESIGNER>(); designers = 'calls my procedure below and comes back with an unsorted list of designers' designers.Sort((x, y) => string.Compare(x.FIRST_NAME, y.LAST_NAME)); Query goes as follows: List<TBLDESIGNER> designer = null; using (SOAE strikeOffContext = new SOAE()) { //Invoke the query designer = AdminDelegates.selectDesignerDesigns.Invoke(strikeOffContext).ByActive(active).ByAdmin(admin).ToList(); } Delegate: public static Func<SOAE, IQueryable<TBLDESIGNER>> selectDesignerDesigns = CompiledQuery.Compile<SOAE, IQueryable<TBLDESIGNER>>( (designer) => from c in designer.TBLDESIGNER.Include("TBLDESIGN") orderby c.FIRST_NAME ascending select c); Filter ByActive: public static IQueryable<TBLDESIGNER> ByActive(this IQueryable<TBLDESIGNER> qry, bool active) { //Return the filtered IQueryable object return from c in qry where c.ACTIVE == active select c; } Filter ByAdmin: public static IQueryable<TBLDESIGNER> ByAdmin(this IQueryable<TBLDESIGNER> qry, bool admin) { //Return the filtered IQueryable object return from c in qry where c.SITE_ADMIN == admin select c; } Thanks in advance, Billy

    Read the article

  • Creating reusable chunks of Linq to SQL

    - by tia
    Hi, I am trying to break up horrible linq to sql queries to make them a bit more readable. Say I want to return all orders for product which in the previous year had more than 100 orders. So, original query is: from o in _context.Orders where (from o1 in _context.Orders where o1.Year == o.Year - 1 && o1.Product == o.Product select o1).Count() > 100 select o; Messy. What I'd like to be able to do is to be able to break it down, eg: private IEnumerable<Order> LastSeasonOrders(Order order) { return (from o in _context.Orders where o.Year == order.Year - 1 && o.Product == order.Product select o); } which then lets me change the original query to: from o in _context.Orders where LastSeasonOrders(o).Count() > 100 select o; This doesn't seem to work, as I get method Blah has no supported translation to SQL when the query is run. Any quick tips on the correct way to achieve this?

    Read the article

  • LINQ to SQL Queries odd Materialization

    - by ptoinson
    I ran across an interesting Linq to SQL, uh, feature, the other day. Perhaps someone can give me a logical explanation for the reasoning behind the results. Take the code below as my example which utilizes the AdventureWorks database setup in a Linq to SQL DataContext. This is a clip from my unit test. The resulting customer returned from a call to both CustomerQuery_Test_01() and CustomerQuery_Test_02() is the same. However, the query executed on the SQLServer are different is a major way. The method CustomerQuery_Test_01 us causing the entire Customer table to be materialized, which the call to CustomerQuery_Test_02 is only causing the single customer to be materialized. The resulting SQL Queries are at the bottom of this post. Anyone have a good reason for this? To me, it was highly non-intuitive. protected virtual Customer GetByPrimaryKey(Func<Customer, bool> keySelection) { AdventureWorksDataContext context = new AdventureWorksDataContext(); return (from r in context.Customers select r).SingleOrDefault(keySelection); } [TestMethod] public void CustomerQuery_Test_01() { Customer customer = GetByPrimaryKey(c => c.CustomerID == 2); } [TestMethod] public void CustomerQuery_Test_02() { AdventureWorksDataContext context = new AdventureWorksDataContext(); Customer customer = (from r in context.Customers select r).SingleOrDefault(c => c.CustomerID == 2); } Query for CustomerQuery_Test_01 (notice the lack of a where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] Query for CustomerQuery_Test_02 (notice the where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] WHERE [t0].[CustomerID] = @p0

    Read the article

  • Mysql 100% CPU + Slow query

    - by felipeclopes
    I'm using the RDS database from amazon with a some very big tables, and yesterday I started to face 100% CPU utilisation on the server and a bunch of slow query logs that were not happening before. I tried to check the queries that were running and faced this result from the explain command +----+-------------+-------------------------------+--------+----------------------------------------------------------------------------------------------+---------------------------------------+---------+-----------------------------------------------------------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------------------------------+--------+----------------------------------------------------------------------------------------------+---------------------------------------+---------+-----------------------------------------------------------------+------+----------------------------------------------+ | 1 | SIMPLE | businesses | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index; Using temporary; Using filesort | | 1 | SIMPLE | activities_businesses | ref | PRIMARY,index_activities_users_on_business_id,index_tweets_users_on_tweet_id_and_business_id | index_activities_users_on_business_id | 9 | const | 2252 | Using index condition; Using where | | 1 | SIMPLE | activities_b_taggings_975e9c4 | ref | taggings_idx | taggings_idx | 782 | const,myapp_production.activities_businesses.id,const | 1 | Using index condition; Using where | | 1 | SIMPLE | activities | eq_ref | PRIMARY,index_activities_on_created_at | PRIMARY | 8 | myapp_production.activities_businesses.activity_id | 1 | Using where | +----+-------------+-------------------------------+--------+----------------------------------------------------------------------------------------------+---------------------------------------+---------+-----------------------------------------------------------------+------+----------------------------------------------+ Also checkin in the process list, I got something like this: +----+-----------------+-------------------------------------+----------------------------+---------+------+--------------+------------------------------------------------------------------------------------------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+-----------------+-------------------------------------+----------------------------+---------+------+--------------+------------------------------------------------------------------------------------------------------+ | 1 | my_app | my_ip:57152 | my_app_production | Sleep | 0 | | NULL | | 2 | my_app | my_ip:57153 | my_app_production | Sleep | 2 | | NULL | | 3 | rdsadmin | localhost:49441 | NULL | Sleep | 9 | | NULL | | 6 | my_app | my_other_ip:47802 | my_app_production | Sleep | 242 | | NULL | | 7 | my_app | my_other_ip:47807 | my_app_production | Query | 231 | Sending data | SELECT my_fields... | | 8 | my_app | my_other_ip:47809 | my_app_production | Query | 231 | Sending data | SELECT my_fields... | | 9 | my_app | my_other_ip:47810 | my_app_production | Query | 231 | Sending data | SELECT my_fields... | | 10 | my_app | my_other_ip:47811 | my_app_production | Query | 231 | Sending data | SELECT my_fields... | | 11 | my_app | my_other_ip:47813 | my_app_production | Query | 231 | Sending data | SELECT my_fields... | ... So based on the numbers, it looks like there is no reason to have a slow query, since the worst execution plan is the one that goes through 2k rows which is not much. Edit 1 Another information that might be useful is the slow query_log SET timestamp=1401457485; SELECT my_query... # User@Host: myapp[myapp] @ ip-10-195-55-233.ec2.internal [IP] Id: 435 # Query_time: 95.830497 Lock_time: 0.000178 Rows_sent: 0 Rows_examined: 1129387 Edit 2 After profiling, I got this result. The result have approximately 250 rows with two columns each. +----------------------+----------+ | state | duration | +----------------------+----------+ | Sending data | 272 | | removing tmp table | 0 | | optimizing | 0 | | Creating sort index | 0 | | init | 0 | | cleaning up | 0 | | executing | 0 | | checking permissions | 0 | | freeing items | 0 | | Creating tmp table | 0 | | query end | 0 | | statistics | 0 | | end | 0 | | System lock | 0 | | Opening tables | 0 | | logging slow query | 0 | | Sorting result | 0 | | starting | 0 | | closing tables | 0 | | preparing | 0 | +----------------------+----------+ Edit 3 Adding query as requested SELECT activities.share_count, activities.created_at FROM `activities_businesses` INNER JOIN `businesses` ON `businesses`.`id` = `activities_businesses`.`business_id` INNER JOIN `activities` ON `activities`.`id` = `activities_businesses`.`activity_id` JOIN taggings activities_b_taggings_975e9c4 ON activities_b_taggings_975e9c4.taggable_id = activities_businesses.id AND activities_b_taggings_975e9c4.taggable_type = 'ActivitiesBusiness' AND activities_b_taggings_975e9c4.tag_id = 104 AND activities_b_taggings_975e9c4.created_at >= '2014-04-30 13:36:44' WHERE ( businesses.id = 1 ) AND ( activities.created_at > '2014-04-30 13:36:44' ) AND ( activities.created_at < '2014-05-30 12:27:03' ) ORDER BY activities.created_at; Edit 4 There may be a chance that the indexes are not being applied due to difference in column type between the taggings and the activities_businesses, on the taggable_id column. mysql> SHOW COLUMNS FROM activities_businesses; +-------------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | activity_id | bigint(20) | YES | MUL | NULL | | | business_id | bigint(20) | YES | MUL | NULL | | +-------------+------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec) mysql> SHOW COLUMNS FROM taggings; +---------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | tag_id | int(11) | YES | MUL | NULL | | | taggable_id | bigint(20) | YES | | NULL | | | taggable_type | varchar(255) | YES | | NULL | | | tagger_id | int(11) | YES | | NULL | | | tagger_type | varchar(255) | YES | | NULL | | | context | varchar(128) | YES | | NULL | | | created_at | datetime | YES | | NULL | | +---------------+--------------+------+-----+---------+----------------+ So it is examining way more rows than it shows in the explain query, probably because some indexes are not being applied. Do you guys can help m with that?

    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

  • 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

  • Problem with Mapping Linq-to-Sql on different Types

    - by csharpnoob
    Hi, maybe someone can help. I want to have on mapped Linq-Class different Datatype. This is working: private System.Nullable<short> _deleted = 1; [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)] public System.Nullable<short> deleted { get { return this._deleted; } set { this._deleted = value; } } Sure thing. But no when i want to place some logic for boolean, like this: private System.Nullable<short> _deleted = 1; [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)] public bool deleted { get { if (this._deleted == 1) { return true; } return false; } set { if(value == true) { this._deleted = (short)1; }else { this._deleted = (short)0; } } } I get always runtime error: [TypeLoadException: GenericArguments[2], "System.Nullable`1[System.Int16]", on 'System.Data.Linq.Mapping.PropertyAccessor+Accessor`3[T,V,V2]' violates the constraint of type parameter 'V2'.] I can't change the database to bit.. I need to have casting in mapping class.

    Read the article

  • c# linq to xml to list

    - by WtFudgE
    I was wondering if there is a way to get a list of results into a list with linq to xml. If I would have the following xml for example: <?xml version="1.0"?> <Sports xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SportPages> <SportPage type="test"> <LinkPage> <IDList> <string>1</string> <string>2</string> </IDList> </LinkPage> </SportPage> </SportPages> </Sports> How could I get a list of strings from the IDList? I'm fairly new to linq to xml so I just tried some stuff out, I'm currently at this point: var IDs = from sportpage in xDoc.Descendants("SportPages").Descendants("SportPage") where sportpage.Attribute("type").Value == "Karate" select new { ID = sportpage.Element("LinkPage").Element("IDList").Elements("string") }; But the var is to chaotic to read decently. Isn't there a way I could just get a list of strings from this? Thanks

    Read the article

  • ASP MVC C#: LINQ Foreign Key Constraint conflicts

    - by wh0emPah
    I'm having a problem with LINQ. I have 2 tables (Parent-child relation) Table1: Events (EventID, Description) Table2: Groups (GroupID, EventID(FK), Description) Now i want to create an Event an and a child. Event e = new Event(); e.Description = "test"; Datacontext.Events.InsertOnSubmit(event) Group g = new Group(); g.Description = "test2"; g.EventID = e.EventID; Datacontext.Groups.InsertOnSubmit(g); Datacontext.SubmitChanges(); When i debug, i can see that after inserting the event. the EventID has gotten a new value (auto increment). But when Datacontext.SubmitChanges(); gets called. I get the following exception "The INSERT statement conflicted with the FOREIGN KEY constraint ... I know this can be solved by creating a relation in the LINQ diagram between Events and groups. And then setting the entity itself. But i don't want to load the events everytime i ask a list of groups. All i need is some way that when inserting the group fails, the event insert won't be comitted in the database. Sorry if this is a bit unclear, My english isn't really good. Thanks in advance!

    Read the article

  • Tracking Down a Stack Overflow in My Linq Query

    - by Lazarus
    I've written the following Linq query: IQueryable<ISOCountry> entries = (from e in competitorRepository.Competitors join c in countries on e.countryID equals c.isoCountryCode where !e.Deleted orderby c.isoCountryCode select new ISOCountry() { isoCountryCode = e.countryID, Name = c.Name }).Distinct(); The objective is to retrieve a list of the countries represented by the competitors found in the system. 'countries' is an array of ISOCountry objects explicitly created and returned as an IQueryable (ISOCountry is an object of just two strings, isoCountryCode and Name). Competitors is an IQueryable which is bound to a database table through Linq2SQL though I created the objects from scratch and used the Linq data mapping decorators. For some reason this query causes a stack overflow when the system tries to execute it. I've no idea why, I've tried trimming the Distinct, returning an anonymous type of the two strings, using 'select c', all result in the overflow. The e.CountryID value is populated from a dropdown that was in itself populated from the IQueryable so I know the values are appropriate but even if not I wouldn't expect a stack overflow. Can anyone explain why the overflow is occurring or give good speculation as to why it might be happening? EDIT As requested, code for ISOCountry: public class ISOCountry { public string isoCountryCode { get; set; } public string Name { get; set; } }

    Read the article

  • LINQ to XML via C#

    - by user70192
    Hello, I'm new to LINQ. I understand it's purpose. But I can't quite figure it out. I have an XML set that looks like the following: <Results> <Result> <ID>1</ID> <Name>John Smith</Name> <EmailAddress>[email protected]</EmailAddress> </Result> <Result> <ID>2</ID> <Name>Bill Young</Name> <EmailAddress>[email protected]</EmailAddress> </Result> </Results> I have loaded this XML into an XDocument as such: string xmlText = GetXML(); XDocument xml = XDocument.Parse(xmlText); Now, I'm trying to get the results into POCO format. In an effort to do this, I'm currently using: var objects = from results in xml.Descendants("Results") select new Results // I'm stuck How do I get a collection of Result elements via LINQ? I'm particularly confused about navigating the XML structure at this point in my code. Thank you!

    Read the article

  • Getting values from DataGridView back to XDocument (using LINQ-to-XML)

    - by Pretzel
    Learning LINQ has been a lot of fun so far, but despite reading a couple books and a bunch of online resources on the topic, I still feel like a total n00b. Recently, I just learned that if my query returns an Anonymous type, the DataGridView I'm populating will be ReadOnly (because, apparently Anonymous types are ReadOnly.) Right now, I'm trying to figure out the easiest way to: Get a subset of data from an XML file into a DataGridView, Allow the user to edit said data, Stick the changed data back into the XML file. So far I have Steps 1 and 2 figured out: public class Container { public string Id { get; set; } public string Barcode { get; set; } public float Quantity { get; set; } } // For use with the Distinct() operator public class ContainerComparer : IEqualityComparer<Container> { public bool Equals(Container x, Container y) { return x.Id == y.Id; } public int GetHashCode(Container obj) { return obj.Id.GetHashCode(); } } var barcodes = (from src in xmldoc.Descendants("Container") where src.Descendants().Count() > 0 select new Container { Id = (string)src.Element("Id"), Barcode = (string)src.Element("Barcode"), Quantity = float.Parse((string)src.Element("Quantity").Attribute("value")) }).Distinct(new ContainerComparer()); dataGridView1.DataSource = barcodes.ToList(); This works great at getting the data I want from the XML into the DataGridView so that the user has a way to manipulate the values. Upon doing a Step-thru trace of my code, I'm finding that the changes to the values made in DataGridView are not bound to the XDocument object and as such, do not propagate back. How do we take care of Step 3? (getting the data back to the XML) Is it possible to Bind the XML directly to the DataGridView? Or do I have to write another LINQ statement to get the data from the DGV back to the XDocument? Suggstions?

    Read the article

  • Linq join with an inner collection

    - by bronze
    Hi, I am trying a LINQ to Object query on 2 collections Customer.Orders Branches.Pending.Orders (Collection within a collection) I want to output each branch which is yet to deliver any order of the customer. var match = from order in customer.Orders join branch in Branches on order equals branch.Pending.Orders select branch; This does not work, I get : The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'. From my search, I think this is because Order or collection of Orders does not implement equals. If this query worked, it will still be wrong, as it will return a branch if the customer's and pending orders match exactly. I want a result if any of the order matches. I am learning Linq, and looking for a approach to address such issues, rather than the solution itself. I would have done this in SQL like this; SELECT b.branch_name from Customers c, Branches b, Orders o WHERE c.customer_id = o.customer_id AND o.branch_id = b.branch_id AND c.customer_id = 'my customer' AND o.order_status = 'pending'

    Read the article

  • Linq is returning too many results when joined

    - by KallDrexx
    In my schema I have two database tables. relationships and relationship_memberships. I am attempting to retrieve all the entries from the relationship table that have a specific member in it, thus having to join it with the relationship_memberships table. I have the following method in my business object: public IList<DBMappings.relationships> GetRelationshipsByObjectId(int objId) { var results = from r in _context.Repository<DBMappings.relationships>() join m in _context.Repository<DBMappings.relationship_memberships>() on r.rel_id equals m.rel_id where m.obj_id == objId select r; return results.ToList<DBMappings.relationships>(); } _Context is my generic repository using code based on the code outlined here. The problem is I have 3 records in the relationships table, and 3 records in the memberships table, each membership tied to a different relationship. 2 membership records have an obj_id value of 2 and the other is 3. I am trying to retrieve a list of all relationships related to object #2. When this linq runs, _context.Repository<DBMappings.relationships>() returns the correct 3 records and _context.Repository<DBMappings.relationship_memberships>() returns 3 records. However, when the results.ToList() executes, the resulting list has 2 issues: 1) The resulting list contains 6 records, all of type DBMappings.relationships(). Upon further inspection there are 2 for each real relationship record, both are an exact copy of each other. 2) All relationships are returned, even if m.obj_id == 3, even though objId variable is correctly passed in as 2. Can anyone see what's going on because I've spent 2 days looking at this code and I am unable to understand what is wrong. I have joins in other linq queries that seem to be working great, and my unit tests show that they are still working, so I must be doing something wrong with this. It seems like I need an extra pair of eyes on this one :)

    Read the article

  • Using conditionals in Linq Programatically

    - by Mike B
    I was just reading a recent question on using conditionals in Linq and it reminded me of an issue I have not been able to resolve. When building Linq to SQL queries programatically how can this be done when the number of conditionals is not known until runtime? For instance in the code below the first clause creates an IQueryable that, if executed, would select all the tasks (called issues) in the database, the 2nd clause will refine that to just issues assigned to one department if one has been selected in a combobox (Which has it's selected item bound to the departmentToShow property). How could I do this using the selectedItems collection instead? IQueryable<Issue> issuesQuery; // Will select all tasks issuesQuery = from i in db.Issues orderby i.IssDueDate, i.IssUrgency select i; // Filters out all other Departments if one is selected if (departmentToShow != "All") { issuesQuery = from i in issuesQuery where i.IssDepartment == departmentToShow select i; } By the way, the above code is simplified, in the actual code there are about a dozen clauses that refine the query based on the users search and filter settings.

    Read the article

  • EF/LINQ: Where() against a property of a subtype

    - by ladenedge
    I have a set of POCOs, all of which implement the following simple interface: interface IIdObject { int Id { get; set; } } A subset of these POCOs implement this additional interface: interface IDeletableObject : IIdObject { bool IsDeleted { get; set; } } I have a repository hierarchy that looks something like this: IRepository<T <: BasicRepository<T <: ValidatingRepository<T (where T is IIdObject) I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject have a Where(p => p.IsDeleted == false) filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects. My first attempt looked like this: public override IQueryable<T> Query() { return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false); } This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types." I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand: interface IQueryFilter<out T> // error { Expression<Func<T, bool>> GetFilter(); } I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try. Thanks very much in advance!

    Read the article

  • LINQ to objects: Is there

    - by Charles
    I cannot seem to find a way to have LINQ return the value from a specified accessor. I know the name of the accessors for each object, but am unsure if it is possible to pass the requested accessor as a variable or otherwise achieve the desired refactoring. Consider the following code snippet: // "value" is some object with accessors like: format, channels, language row = new List<String> { String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.format).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.channels).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.language).ToArray()), // ... } I'd like to refactor this into a method that uses the specified accessor, or perhaps pass a delegate, though I don't see how that could work. string niceRefactor(myObj myObject, string /* or whatever type */ ____ACCESSOR) { return String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.____ACCESSOR).ToArray()); } I have written a decent amount of C#, but am still new to the magic of LINQ. Is this the right approach? How would you refactor this?

    Read the article

  • LINQ to SQL: Reusable expression for property?

    - by coenvdwel
    Pardon me for being unable to phrase the title more exact. Basically, I have three LINQ objects linked to tables. One is Product, the other is Company and the last is a mapping table Mapping to store what Company sells which products and by which ID this Company refers to this Product. I am now retrieving a list of products as follows: var options = new DataLoadOptions(); options.LoadWith<Product>(p => p.Mappings); context.LoadOptions = options; var products = ( from p in context.Products select new { ProductID = p.ProductID, //BackendProductID = p.BackendProductID, BackendProductID = (p.Mappings.Count == 0) ? "None" : (p.Mappings.Count > 1) ? "Multiple" : p.Mappings.First().BackendProductID, Description = p.Description } ).ToList(); This does a single query retrieving the information I want. But I want to be able to move the logic behind the BackendProductID into the LINQ object so I can use the commented line instead of the annoyingly nested ternary operator statements for neatness and re-usability. So I added the following property to the Product object: public string BackendProductID { get { if (Mappings.Count == 0) return "None"; if (Mappings.Count > 1) return "Multiple"; return Mappings.First().BackendProductID; } } The list is still the same, but it now does a query for every single Product to get it's BackendProductID. The code is neater and re-usable, but the performance now is terrible. What I need is some kind of Expression or Delegate but I couldn't get my head around writing one. It always ended up querying for every single product, still. Any help would be appreciated!

    Read the article

  • Linq generic Expression in query on "element" or on IQueryable (multiple use)

    - by Bogdan Maxim
    Hi, I have the following expression public static Expression<Func<T, bool>> JoinByDateCheck<T>(T entity, DateTime dateToCheck) where T : IDateInterval { return (entityToJoin) => entityToJoin.FromDate.Date <= dateToCheck.Date && (entityToJoin.ToDate == null || entityToJoin.ToDate.Value.Date >= dateToCheck.Date); } IDateInterval interface is defined like this: interface IDateInterval { DateTime FromDate {get;} DateTime? ToDate {get;} } and i need to apply it in a few ways: (1) Query on Linq2Sql Table: var q1 = from e in intervalTable where FunctionThatCallsJoinByDateCheck(e, constantDateTime) select e; or something like this: intervalTable.Where(FunctionThatCallsJoinByDateCheck(e, constantDateTime)) (2) I need to use it in some table joins (as linq2sql doesn't provide comparative join): var q2 = from e1 in t1 join e2 in t2 on e1.FK == e2.PK where OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate) or var q2 = from e1 in t1 from e2 in t2 where e1.FK == e2.PK && OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate) (3) I need to use it in some queries like this: var q3 = from e in intervalTable.FilterFunctionThatCallsJoinByDateCheck(constantDate); Dynamic linq is not something that I can use, so I have to stick to plain linq. Thank you Clarification: Initially I had just the last method (FilterFunctionThatCallsJoinByDateCheck(this IQueryable<IDateInterval> entities, DateTime dateConstant) ) that contained the code from the expression. The problem is that I get a SQL Translate exception if I write the code in a method and call it like that. All I want is to extend the use of this function to the where clause (see the second query in point 2)

    Read the article

  • Linq-to-SQL: Ignore null parameters from WHERE clause

    - by Peter Bridger
    The query below should return records that either have a matching Id supplied in ownerGroupIds or that match ownerUserId. However is ownerUserId is null, I want this part of the query to be ignored. public static int NumberUnderReview(int? ownerUserId, List<int> ownerGroupIds) { return ( from c in db.Contacts where c.Active == true && c.LastReviewedOn <= DateTime.Now.AddDays(-365) && ( // Owned by user !ownerUserId.HasValue || c.OwnerUserId.Value == ownerUserId.Value ) && ( // Owned by group ownerGroupIds.Count == 0 || ownerGroupIds.Contains( c.OwnerGroupId.Value ) ) select c ).Count(); } However when a null is passed in for ownerUserId then I get the following error: Nullable object must have a value. I get a tingling I may have to use a lambda expression in this instance?

    Read the article

  • Linq Paging - How to incorporate total record count

    - by Billy Logan
    Hello everyone, I am trying to figure out the best way of getting the record count will incorporating paging. I need this value to figure out the total page count given a page size and a few other variables. This is what i have so far which takes in the starting row and the page size using the skip and take statements. promotionInfo = (from p in matches orderby p.PROMOTION_NM descending select p).Skip(startRow).Take(pageSize).ToList(); I know i could run another query, but figured there may be another way of achieving this count without having to run the query twice. Thanks in advance, Billy

    Read the article

  • Using LINQ Group By to return new XElements

    - by Jon
    I have the following code and got myself confused: I have a query that returns a set of records that have been identified as duplicates and I then want to create a XElement for each one. This should be done in one query I think but I'm now lost. var f = (from x in MyDocument.Descendants("RECORD") where itemsThatWasDuplicated.Contains((int)x.Element("DOCUMENTID")) group x by x.Element("DOCUMENTID").Value into g let item = g.Skip(1) //Ignore first as that is the valid one select item ); var errorQuery = (from x in f let sequenceNumber = x.Element("DOCUMENTID").Value let detail = "Sequence number " + sequenceNumber + " was read more than once" select new XElement("ERROR", new XElement("DATETIME", time), new XElement("DETAIL", detail), new XAttribute("TYPE", "DUP"), new XElement("ID", x.Element("ID").Value) ) );

    Read the article

  • Linq - How to query specific columns and return a lists

    - by Billy Logan
    Hello Everyone, I am trying to write a linq query that will only return certain columns from my entity object into a list object. Below is my code which produces an error(can't implicitly convert a generic list of anonymous types to a generic list of type TBLPROMOTION): List<TBLPROMOTION> promotionInfo = null; promotionInfo = (from p in matches orderby p.PROMOTION_NM descending select new { p.EFFECTIVE_DT, p.EXPIRE_DT, p.IS_ACTIVE, p.PROMOTION_DESC, p.PROMOTION_ID, p.PROMOTION_NM }).ToList(); What would be the best way to accomplish this. I do not want to do a "select p" in this case and return all the columns associated with the query. thanks in advance, Billy

    Read the article

  • How to Expression.Invoke an arbitrary LINQ 2 SQL Query

    - by Remus Rusanu
    Say I take an arbitrary LINQ2SQL query's Expression, is it possible to invoke it somehow? MyContext ctx1 = new MyContext("..."); var q = from t in ctx1.table1 where t.id = 1 select t; Expression qe = q.Expression; var res = Expression.Invoke(qe); This throws ArgumentException "Expression of type System.Linq.IQueryable`1[...]' cannot be invoked". My ultimate goal is to evaluate the same query on several different data contexts.

    Read the article

  • Custom Grid LINQ to SQL help

    - by user488361
    Following is my custome cotrol grid... public partial class LinqGrid : UserControl { object tmpDataTable = new object(); public LinqGrid() { InitializeComponent(); } public void Bind(System.Data.Linq.Table listSource) where T : class { Project.dbClassesDataContext dbc = new Project.dbClassesDataContext(); tmpDataTable = listSource; var query = (from c in listSource select c); dgvRecords.DataSource = query.Take(10).ToList(); } private void btnNext_Click(object sender, EventArgs e) { // now what i have to do here if i want next 10 records.....means how to retrive tmpDataTable object here... ??? i can't find Type of variable....?? plz help me.... } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >