Search Results

Search found 7676 results on 308 pages for 'linq extensions'.

Page 51/308 | < Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >

  • Filter across 2 lists using LINQ

    - by Ajit Goel
    I have two lists: a. requestedAmenities b. units with amenities. I want to filter those units that have any one of the "requested amenities". I have tried to achieve the same result using foreach loops but I believe it should be much easier using LINQ. Can someone please help\advice? UnitAmenities unitSearchRequestAmenities = unitSearchRequest.Amenities; var exactMatchApartmentsFilteredByAmenities= new Units(); IEnumerable<string> requestAmenitiesIds = unitSearchRequestAmenities.Select(element => element.ID); foreach (var unitCounter in ExactMatchApartments) { IEnumerable<string> unitAmenities = unitCounter.Amenities.Select(element => element.ID); foreach (var requestAmenityId in requestAmenitiesIds) { foreach (var unitAmenity in unitAmenities) { if (requestAmenityId == unitAmenity) { exactMatchApartmentsFilteredByAmenities.Add(unitCounter); //break to the outmost foreach loop } } } }

    Read the article

  • See if item exists once in Enumerable (Linq)

    - by Stacey
    Given a list... class Item { public Name { get; set; } } List<Item> items = new List<Item> { new Item() { Name = "Item 1" }, new Item() { Name = "Item 1" }, new Item() { Name = "Item 2" }, new Item() { Name = "Item 3" } } List<Item> listing = new List<Item> { new Item() { Name = "Item 1" }, new Item() { Name = "Item 2" }, new Item() { Name = "Item 3" } new Item() { Name = "Item 4" } } etc. I need to create a third array that will cancel out double instances between the two; however items with "Name 1" are both the same, but different 'instances'. So the third List should have 1 instance of Item 1, since 'items' had 2 instances. Any ideas of how this can be done through Linq?

    Read the article

  • Call Method from LinQ query.

    - by Jitendra Jadav
    Hello Everybody, I am using Linq query and call method Like.. oPwd = objDecryptor.DecryptIt((c.Password.ToString()) it will return null value. Means this will not working. how I Resolve this. Thanks.. var q = from s in db.User join c in db.EmailAccount on s.UserId equals c.UserId join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId where s.UserId == UserId && c.EmailId == EmailId select new { oUserId = s.UserId, oUserName = s.Name, oEmailId = c.EmailId, oEmailAccId = c.EmailAccId, oPwd = objDecryptor.DecryptIt(c.Password.ToString()), oServerName = d.ServerName, oServerAdd = d.ServerAddress, oPOPSettingId = d.POPSettingsId, };

    Read the article

  • Linq Distinct() by name for populate a dropdown list with name and value

    - by AndreMiranda
    I'm trying to populate a Drop down list with pharmaceutical companies, like Bayer, Medley etc. And, I'm getting theses names from DB and theses names are repeated in DB, but with different id's. I'm trying to use Linq Distinct(), but I don't want to use the equality comparer. Is there another way? My drop down list must be filled with the id and the name of the company. I'm trying something like: var x = _partnerService .SelectPartners() .Select(c => new {codPartner = c.codPartner, name = c.name}) .Distinct(); This is showing repeated companies in ddl. thanks!

    Read the article

  • System.Linq.Dynamic and DateTime

    - by Matthew Hood
    I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0. It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. The very simple test code is items = items.Where(string.Format(@" {0} {1}{2}{1} ", searchField, delimiter, searchString)); Where searchField will be for example start_date and the data type is DateTime, delimiter is " (tried with nothing as well) and searchString will be 01-Jan-2009 (tried with 01/01/2009 as well) and items is an IQueryable from LinqToSql. Is there a way of specifying the data type in a dynamic where, or is there a better approach. It is currently already using some reflection to work out what type of delimiter is required.

    Read the article

  • Linq Query Giving Error

    - by user275561
    I am getting this error when I use the Linq expression of var emp = _testModel.Where(m => m.Date == DateTime.Now).Select(m=>m); 'System.Collections.Generic.IEnumerable' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?). I have google'd and looked everywhere by I have no idea what it is talking about? It doesn't throw an exception. The only way I found out about this was stepping through the expression.

    Read the article

  • [LINQ noob] Please help me convert this Python 3.x snippet to .net LINQ.

    - by Hamish Grubijan
    I want to sort elements of a HashSet<string> and join them by a ; character. Python interpreter version: >>> st = {'jhg', 'uywer', 'nbcm', 'utr'} >>> strng = ';'.join(sorted(s)) >>> strng 'ASD;anmbh;ashgg;jhghjg' C# signature of a method I seek: private string getVersionsSorted(HashSet<string> versions); I can do this without using Linq, but I really want to learn it better. Many thanks!

    Read the article

  • linq and contains

    - by kusanagi
    i have func public PageOfList<ConsaltQuestion> Filter(int? type, int pageId, EntityCollection<ConsaltCost> ConsaltRoles) { // return _dataContext.ConsaltQuestion.Where((o => o.Type == type || type == null) && (o=>o.Paid == paid)); return (from i in _dataContext.ConsaltQuestion where ((i.Type == type || type == null) && (i.Paid == true) && (ConsaltRoles.Contains(ConsaltCostDetails(i.Type.Value)))) select i).ToList().ToPageOfList(pageId, 20); } it return error LINQ to Entities does not recognize the method 'Boolean Contains(mrhome.Models.ConsaltCost)' method, and this method cannot be translated into a store expression. how can i fix it?

    Read the article

  • Need help with a LINQ ArgumentOutOfRangeException in C#

    - by Christopher Klein
    Hi there, Hoping this is a nice softball of a question for a friday but I have the following line of code: //System.ArgumentOutOfRangeException generated if there is no matching data currentAnswers = new CurrentAnswersCollection().Where("PARTICIPANT_ID", 10000).Load()[0]; CurrentAnswersCollection is a strongly-typed collection populated by a view going back to my database. The problem of course is that if there is not a corresponding PARTICIPANT_ID = 10000 I get the error message. Is there a better way to write this so that I wouldn't get the error message at all? I just dont know enough about LINQ syntax to know if I can test for the existance first? thanks.

    Read the article

  • Make a usable Join relationship with LINQ on top of a database CSV design error

    - by jdk
    I'm looking for a way to fix and/or abstract away a comma-separated values (CSV) list in a database field in order to reconstruct a usable relationship such that I can properly join the two tables below and query them using LINQ and its Join method. Following is a sample showing the Person table and CsvArticleIds field having a CSV value to represent a one-to-many association with Article records. TABLE [dbo].[Person] Id Name CsvArticleIds -- ---------- -------- 1 Joe "15,22" 5 Ed "22" 10 Arnie "8,15,22" ^^^(Of course a link table should have been created; nonetheless the relationship with articles is trapped inside that list of CSV values.) TABLE [dbo].[Article] Id Title -- ---------- 8 Beginning C# 15 A Historic look at Programming in the 90s 22 Gardening in January Additional Info the fix can be at any level: C#.NET or SQL Server something easy because I will be repeating the solution for many other CSV values in other tables. Elegant is nice too. not looking for efficiency because this is part of a one-time data migration task and can take as long as it wants to run.

    Read the article

  • Use LINQ to SQL results inside SQL Server stored procedure

    - by ifwdev
    Note: I'm not trying to call a SQL Server stored proc using a L2SQL datacontext. I use LINQPad for some fairly complex "reporting" that takes L2SQL output saved to an Array and is processed further. For example, it's usually much easier to do multiple levels of grouping with LINQ to Objects instead of trying to optimize a T-SQL query to run in a reasonable amount of time. What would be the easiest way to take the end result of one of these "applications" and use that in a SQL Server 2008 stored proc? The idea is to use the data for a Reporting Services Report, rather than copying and pasting into Excel (manual labor). The reports need to be accessible on the report server (not using the Report Server control in an application). I could output CSV and read that somehow via command line exec, but that seems like a hack. Thanks for your help.

    Read the article

  • Linq Query ignore empty parameters

    - by Cj Anderson
    How do I get Linq to ignore any parameters that are empty? So Lastname, Firstname, etc? If I have data in all parameters it works fine. refinedresult = From x In theresult _ Where x.<thelastname>.Value.TestPhoneElement(LastName) Or _ x.<thefirstname>.Value.TestPhoneElement(FirstName) Or _ x.<id>.Value.TestPhoneElement(Id) Or _ x.<number>.Value.TestPhoneElement(Telephone) Or _ x.<location>.Value.TestPhoneElement(Location) Or _ x.<building>.Value.TestPhoneElement(building) Or _ x.<department>.Value.TestPhoneElement(Department) _ Select x Public Function TestPhoneElement(ByVal parent As String, ByVal value2compare As String) As Boolean 'find out if a value is null, if not then compare the passed value to see if it starts with Dim ret As Boolean = False If String.IsNullOrEmpty(parent) Then Return False End If If String.IsNullOrEmpty(value2compare) Then Return ret Else ret = parent.ToLower.StartsWith(value2compare.ToLower.Trim) End If Return ret End Function

    Read the article

  • linq to xml and namespaces

    - by scott
    I'm always so excited to get a chance to use linq to xml and then I run into the same PITA issue with namespaces. Not sure what is wrong with me but I can never quite grok what is going on. Basically I just need to get the value of the responseCode element and so far I have had no luck :( <?xml version="1.0" encoding="IBM437"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <ns1:ActionResponse xmlns:ns1="http://cbsv.ssa.gov/ws/datatype"> <ns1:responseCode>0000</ns1:responseCode> <ns1:responseDescription>Successful</ns1:responseDescription> </ns1:ActionResponse> </soapenv:Body> </soapenv:Envelope>

    Read the article

  • DataTable linq query iteration

    - by Ravi
    Hi, I want to Enumerate Linq Query. Below i specified example. EX: DataTable _slidingDataTable = new DataTable("test"); for(int i=0; i<5;i++) { DataRow row = _slidingDataTable.NewRow(); startPosition = DateTime.Now; for(int i=0; i<5;i++) { _slidingDataTable.Columns.Add("TransferTime"); row[columnName] = startPosition ; _slidingDataTable.Columns.Add("TransferData"); row[columnName] = "Test"+i; } _slidingDataTable.Rows.Add(row); } var query1 = from myRow in _slidingDataTable.AsEnumerable() where myRow.Field<DateTime>("TransferTime") == startPosition select myRow; This query output should be collection of rows. How to get collection row & iterate.

    Read the article

  • Linq query: append column to query results

    - by jrubengb
    I am trying to figure out how to append a column to Linq query results based on the max value of the query. Essentially, I want to create an EnumerableRowCollection of DataRows that would include a max value record with the same value for each record. So if i have a hundred records returned through the query, I want to next calculate the max value of one of the fields, then append that max value to the original query table: DataTable dt = new DataTable(); dt = myDataSet.myDataTable; EnumerableRowCollection<DataRow> qrySelectRecords = (from d in dt.AsEnumerable() where d.Field<DateTime>("readingDate") >= startDate && g.Field<DateTime>("readingDate") <= endDate select d); Here's where I need help: double maxValue = qrySelectRecords.Field<double>("field1").Max(); foreach (DataRow dr in qrySelectRecords) { qrySelectRecords.Column.Append(maxValue) }

    Read the article

  • Linq Query to IEnumerable<T> Extension Method

    - by CSharpNoob
    Consider this, class Item { public string ID { get; set;} public string Description { get; set; } } class SaleItem { public string ID { get; set;} public string Discount { get; set; } } var itemsToRemoved = (List<Item>)ViewState["ItemsToRemove"]; // get only rows of ID var query = from i in itemsToRemoved select i.ID; var saleItems= (List<SaleItem>)ViewState["SaleItems"]; foreach (string s in query.ToArray()) { saleItems.RemoveItem(s); } How can I write this LINQ phrase using IEnumerable/List Extension methods // get only rows of ID var query = from i in items select i.ID; thanks in advance.

    Read the article

  • LINQ saving images to varbinary

    - by m4rc
    I'm having issues saving images to a varbinary(Max) field using LINQ. I can save files in the region of 10KB to the database no problems, but when it comes to files bigger than that, it's as though it doesn't even try. I've had a look in the SQL Server Profiler and when the file is around 10KB I can see the full insert statement in the detail pane. However, when the file is a bit bigger, the detail pane doesn't show anything, although any data besides the varbinary field is written to the database. The data is in the Data Object just before SubmitChanges so I can't figure out what's happening between now and then!

    Read the article

  • LINQ to SQl updating primary key field?

    - by Curtis White
    I have a linq to sql table/class that uses a GUID as both a primary key and as foreign key. This problem came up when factoring some code that previously worked. The exception generated is "Operation is not valid due to the current state of the object." The process I use is as such: aspnet_User user() = new aspnet_User(); aspnet_user.childTable = new childTable(); .. set some properties user.Insert() -> my custom method ... @ my custom method using (mycontext dc = new context() ) { user.childTable.ID = (Guid)myNewlyCreatedGuid; } The exception occurs on the assignment childTable.set_UserId().

    Read the article

  • Storing object into cache using Linq classes and velocity

    - by Arun
    I careated couple of linq classes & marked the datacontext as unidirectional. Out of four classes; one is main class while other three are having the one to many relationship with first one; When I load the object of main class & put into the memory OR serialize it into an XML file; I never get the child class data while it is maked as DataContractAttribute. How can I force object to put the child class data into XML file or into cache ?

    Read the article

  • Read Xlement fully using LinQ

    - by Ramya
    Hi, I have an XElement which I am getting after parsing an xml. This XElement needs to be read only when the need arises so, I have stored it in a list for future use. I have to read this XElement using LinQ. XDocument doc = XDocument.Parse(DataManager.offeringElements[index].DataElem.ToString()); var docNode = from dataNode in doc.Descendants("DataLinks") select new { Offering = dataNode .Element("link").Value, linkUrl = dataNode.Element("link").Attribue ("href").Value }; the Xelement has the following nodes a. Management b. Analytics c. Development My problem is that I am not able to read all the three nodes.I am able to get only the first node. Where am I going wrong?

    Read the article

  • Update through Linq-to-SQL DataContext not working.

    - by Puneet Dudeja
    I have created a small test for updating table using Linq-to-SQL DataContext as follows: using (pessimistic_exampleDataContext db = new pessimistic_exampleDataContext()) { var query = db.test1s.First(t => t.a == 3); if (query.b == "a") query.b = "b"; else query.b = "a"; db.SubmitChanges(); } But after executing this code in a console application in Main method, when I select records from the table, the record is not updated. I have debugged through the code, and it is not even throwing any exception. What can be the problem ?

    Read the article

  • Linq to SQL inheritance and Table per Class - approach needed for multiple roles

    - by Ash Machine
    I am using L2S and an inheritance model for mapping Persons against certain roles. Guy Burstein's excellent blog post explains how to accomplish this: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx However, I have a specific case where a Person has multiple roles. For example 'Jane Doe' is a Contact and a Programmer. In this model, she would need two rows in the People table, one as Contact (PersonType = 1) and one as Programmer (PersonType = 3). If she changes her last name, and that update happens in her role as Contact, I would need to change all instances of 'Jane Doe' to reflect the name change everywhere. What sort of best approach (improved data structure) could be used to change last name within all roles? Finally, I am hoping to avoid overriding each general form update events to include all instances, but that may be the only way. Any suggestions or approaches appreciated.

    Read the article

  • Using multiple databases within one application (ASP.NET MVC, LINQ to SQL)

    - by Alex
    I have a web application made for several groups of people not connected with each other. Instead of using one database for all of them, I'm thinking about making separate databases. This will improve the speed of the queries and make me free from checking to what group the user belongs. But since I'm working with LINQ to SQL, my classes are explicitly connected with the databases, so I will have to make separate DataContexts for all of the databases. So how can I solve this problem? Or should I just not bother and use one database only?

    Read the article

  • LINQ - Using where or join - Performance difference ?

    - by Patrick Säuerl
    Hi Based on this question: http://stackoverflow.com/questions/3013034/what-is-difference-between-where-and-join-in-linq My question is following: Is there a performance difference in the following two statements: from order in myDB.OrdersSet from person in myDB.PersonSet from product in myDB.ProductSet where order.Persons_Id==person.Id && order.Products_Id==product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name }; and from order in myDB.OrdersSet join person in myDB.PersonSet on order.Persons_Id equals person.Id join product in myDB.ProductSet on order.Products_Id equals product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name }; I would always use the second one just because it´s more clear. My question is now, is the first one slower than the second one? Does it build a cartesic product and filters it afterwards with the where clauses ? Thank you.

    Read the article

  • Linq to SQl Stored Procedure Problem( it can't figure out the return type)

    - by chobo2
    Hi I have this SP USE [Test] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[UsersInsert](@UpdatedProdData XML) AS INSERT INTO dbo.UserTable(UserId,UserName,LicenseId,Password,PasswordSalt,Email,IsApproved,IsLockedOut,CreateDate, LastLoginDate,LastLockOutDate,FailedPasswordAttempts,RoleId) SELECT @UpdatedProdData.value('(/ArrayOfUsers/Users/UserId)[1]', 'uniqueidentifier'), @UpdatedProdData.value('(/ArrayOfUsers/Users/UserName)[1]', 'varchar(20)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LicenseId)[1]', 'varchar(50)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/Password)[1]', 'varchar(128)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/PasswordSalt)[1]', 'varchar(128)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/Email)[1]', 'varchar(50)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/IsApproved)[1]', 'bit'), @UpdatedProdData.value('(/ArrayOfUsers/Users/IsLockedOut)[1]', 'bit'), @UpdatedProdData.value('(/ArrayOfUsers/Users/CreateDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LastLoginDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LastLockOutDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/FailedPasswordAttempts)[1]', 'int'), @UpdatedProdData.value('(/ArrayOfUsers/Users/RoleId)[1]', 'int') Now this SP creates just fine. It's when I go to VS2010 and try to drag this SP in my method panel of my linq to sql file in design view. It tells me that it can't figure out the return type. I try to go to the properties but it does not have "none" as a choice and I can't type it in. It should be "none" so how do I set it to "none"?

    Read the article

< Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >