Search Results

Search found 6048 results on 242 pages for 'linq to dataset'.

Page 7/242 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Distinct operator in Linq

    - by Jalpesh P. Vadgama
    Linq operator provides great flexibility and easy way of coding. Let’s again take one more example of distinct operator. As name suggest it will find the distinct elements from IEnumerable. Let’s take an example of array in console application and then we will again print array to see is it working or not. Below is the code for that. In this application I have integer array which contains duplicate elements and then I will apply distinct operator to this and then I will print again result of distinct operators to actually see whether its working or not. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Experiment { class Program { static void Main(string[] args) { int[] intArray = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 }; var uniqueIntegers = intArray.Distinct(); foreach (var uInteger in uniqueIntegers) { Console.WriteLine(uInteger); } Console.ReadKey(); } } } Below is output as expected.. That’s cool..Stay tuned for more.. Happy programming. Technorati Tags: Linq,Distinct

    Read the article

  • Is LINQ to objects a collection of combinators?

    - by Jimmy Hoffa
    I was just trying to explain the usefulness of combinators to a colleague and I told him LINQ to objects are like combinators as they exhibit the same value, the ability to combine small pieces to create a single large piece. Though I don't know that I can call LINQ to objects combinators. I've seen 2 levels of definition for combinator that I generalize as such: A combinator is a function which only uses things passed to it A combinator is a function which only uses things passed to it and other standard atomic functions but not state The first is very rigid and can be seen in the combinatory calculus systems and in haskell things like $ and . and various similar functions meet this rule. The second is less rigid and would allow something like sum as it uses the + function which was not passed in but is standard and not stateful. Though the LINQ extensions in C# use state in their iteration models, so I feel I can't say they're combinators. Can someone who understands the definition of a combinator more thoroughly and with more experience in these realms give a distinct ruling on this? Are my definitions of 'combinator' wrong to begin with?

    Read the article

  • Simplify Your Code with LINQ

    - by dwahlin
    I’m a big fan of LINQ and use it wherever I can to minimize code and make applications easier to maintain overall. I was going through a code file today refactoring it based on suggestions provided by Resharper and came across the following method: private List<string> FilterTokens(List<string> tokens) { var cleanedTokens = new List<string>(); for (int i = 0; i < tokens.Count; i++) { string token = tokens[i]; if (token != null) { cleanedTokens.Add(token); } } return cleanedTokens; }   In looking through the code I didn’t see anything wrong but Resharper was suggesting that I convert it to a LINQ expression: In thinking about it more the suggestion made complete sense because I simply wanted to add all non-null token values into a List<string> anyway. After following through with the Resharper suggestion the code changed to the following. Much, much cleaner and yet another example of why LINQ (and Resharper) rules: private List<string> FilterTokens(IEnumerable<string> tokens) { return tokens.Where(token => token != null).ToList(); }

    Read the article

  • Take,Skip and Reverse Operator in Linq

    - by Jalpesh P. Vadgama
    I have found three more new operators in Linq which is use full in day to day programming stuff. Take,Skip and Reverse. Here are explanation of operators how it works. Take Operator: Take operator will return first N number of element from entities. Skip Operator: Skip operator will skip N number of element from entities and then return remaining elements as a result. Reverse Operator: As name suggest it will reverse order of elements of entities. Here is the examples of operators where i have taken simple string array to demonstrate that. C#, using GeSHi 1.0.8.6 using System; using System.Collections.Generic; using System.Linq; using System.Text;     namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             string[] a = { "a", "b", "c", "d" };                           Console.WriteLine("Take Example");             var TkResult = a.Take(2);             foreach (string s in TkResult)             {                 Console.WriteLine(s);             }               Console.WriteLine("Skip Example");             var SkResult = a.Skip(2);             foreach (string s in SkResult)             {                 Console.WriteLine(s);             }               Console.WriteLine("Reverse Example");             var RvResult = a.Reverse();             foreach (string s in RvResult)             {                 Console.WriteLine(s);             }                       }     } } Parsed in 0.020 seconds at 44.65 KB/s Here is the output as expected. hope this will help you.. Technorati Tags: Linq,Linq-To-Sql,ASP.NET,C#.NET

    Read the article

  • C# DataSet CheckBox Column With DevExpress DataGrid

    - by Goober
    Scenario I have a DevExpress DataGrid which is bound to a DataSet in C#. I want to populate each dataset row to contain a string in the first column and a checkbox in the second. My code below doesn't work quite how I want it to, and I'm not sure why..... The Code As you can see I've declared a dataset, but when I try and pass in a new checkbox object to the 2nd column it just displays the system name for the checkbox. DataSet prodTypeDS = new Dataset(); DataTable prodTypeDT = prodTypeDS.Tables.Add(); prodTypeDT.Columns.Add("MurexID", typeof(string)); prodTypeDT.Columns.Add("Haganise",typeof(CheckBox)); //WHY DOES THIS NOT WORK? //(Displays "System.Windows.Forms.CheckBox, CheckState: 0") //Instead of a checkbox. CheckBox c = new CheckBox(); prodTypeDS.Tables[0].Rows.Add("Test",c); //This doesn't work either.... prodTypeDS.Tables[0].Rows.Add("Test",c.CheckState); ......I hope this is just because it's a DevExpress datagrid....

    Read the article

  • OleDb database to DataSet and back in c#?

    - by Troy
    I'm writing a program that lets a user: Connect to an (arbitrary) View all of the tables in that database in separate DataGridViews Edit them in the program, generate random data, and see the results Choose to commit those changes or revert So I discovered the DataSet class, which looks like it's capable of holding everything that a database would, and I decided that the best thing to do here would be to load everything into one dataset, let the user edit it, and then save the dataset back to the database. The problem is that the only way I can find to load the database tables is this: set = new DataSet(); DataTable schema = connection.GetOleDbSchemaTable( OleDbSchemaGuid.Tables, new string[] { null, null, null, "TABLE" }); foreach (DataRow row in schema.Rows) { string tableName = row.Field<string>("TABLE_NAME"); DataTable dTable = new DataTable(); new OleDbDataAdapter("SELECT * FROM " + tableName, connection).Fill(dTable); dTable.TableName = tableName; set.Tables.Add(dTable); } while it seems like there should be a simpler way given that datasets appear to be designed for exactly this purpose. The real problem though is when I try saving these things. In order to use the OleDbDataAdapter.Update() method, I'm told that I have to provide valid INSERT queries. Doesn't that kind of negate the whole point of having a class to handle this stuff for me? Anyway, I'm hoping somebody can either explain how to load and save a database into a dataset or maybe give me a better idea of how to do what I'm trying to do. I could always parse the commands together myself, but that doesn't seem like the best solution.

    Read the article

  • dataset not getting all the resultant tables i.e multiple tables are not being displayed in dataset

    - by Shantanu Gupta
    How to fill multiple tables in a dataset. I m using a query that returns me four tables. At the frontend I am trying to fill all the four resultant table into dataset. Here is my Query. Query is not complete. But it is just a refrence for my Ques Select * from tblxyz compute sum(col1) suppose this query returns more than one table, I want to fill all the tables into my dataset I am filling result like this con.open(); adp.fill(dset); con.close(); Now when i checks this dataset. It shows me that it has four tables but only first table data is being displayed into it. rest 3 dont even have schema also. What i need to do to get desired output

    Read the article

  • How to fill dataset when sql is returning more than one table

    - by Shantanu Gupta
    How to fill multiple tables in a dataset. I m using a query that returns me four tables. At the frontend I am trying to fill all the four resultant table into dataset. Here is my Query. Query is not complete. But it is just a refrence for my Ques Select * from tblxyz compute sum(col1) suppose this query returns more than one table, I want to fill all the tables into my dataset I am filling result like this con.open(); adp.fill(dset); con.close(); Now when i checks this dataset. It shows me that it has four tables but only first table data is being displayed into it. rest 3 dont even have schema also. What i need to do to get desired output

    Read the article

  • Getting data from array of DataSet objects returned from web service

    - by Sarah Vessels
    I have a web service that I want to access when it is added as a web reference to my C# project. A particular method in the web service takes a SQL query string and returns the results of the query as a custom type. When I add the web service reference, the method shows up as returning DataSet[] instead of the custom type. This is fine provided I can still somehow access the data returned from the query within those DataSet objects. I ran a particular query that should return 6 rows; I got back a DataSet[] array with 6 elements. However, when I iterate over those DataSet objects, none of them has any tables (via the Tables property on the DataSet). What gives? Where is my data? The web service is tested and works when I use it as a data source in a Report Builder 2.0 report. I am able to send an XML SOAP query to the web service and get back XML results containing my data.

    Read the article

  • Parsing a .NET DataSet returned from a .NET Web Service in Java

    - by Chris Dail
    I have to consume a .NET hosted web service from a Java application. Interoperability between the two is usually very good. The problem I'm running into is that the .NET application developer chose to expose data using the .NET DataSet object. There are lots of articles written as to why you should not do this and how it makes interoperability difficult: http://www.hanselman.com/blog/ReturningDataSetsFromWebServicesIsTheSpawnOfSatanAndRepresentsAllThatIsTrulyEvilInTheWorld.aspx http://www.lhotka.net/weblog/ThoughtsOnPassingDataSetObjectsViaWebServices.aspx http://aspnet.4guysfromrolla.com/articles/051805-1.aspx http://www.theserverside.net/tt/articles/showarticle.tss?id=Top5WSMistakes My problem is that despite this not being recommended practice, I am stuck with having to consume a web service returning a DataSet with Java. When you generate a proxy for something like this with anything other than .NET you basically end up with an object that looks like this: @XmlElement(namespace = "http://www.w3.org/2001/XMLSchema", required = true) protected Schema schema; @XmlAnyElement(lax = true) protected Object any; This first field is the actual schema that should describe the DataSet. When I process this using JAX-WS and JAXB in Java, it bring all of XS-Schema in as Java objects to be represented here. Walking the object tree of JAXB is possible but not pretty. The any field represents the raw XML for the DataSet that is in the schema specified by the schema. The structure of the dataset is pretty consistent but the data types do change. I need access to the type information and the schema does vary from call to call. I've though of a few options but none seem like 'good' options. Trying to generate Java objects from the schema using JAXB at runtime seems to be a bad idea. This would be way too slow since it would need to happen everytime. Brute force walk the schema tree using the JAXB objects that JAX-WS brought in. Maybe instead of using JAXB to parse the schema it would be easier to deal with it as XML and use XPath to try and find the type information I need. Are there other options I have not considered? Is there a Java library to parse DataSet objects easily? What have other people done who may have similar situations?

    Read the article

  • DataSet.HasChanges is true even immediately after TableAdapter.Update is run

    - by Nathan Koop
    I've got some legacy dataset code which I'm updating. I'm attempting to determine if the dataset has changes to it so I can properly prompt for a save request. However myDataset.HasChanges() always returns true. In my save method I've edited the code to determine when the dataset get's changes and made the code like this: 1. myBindingSource.EndEdit() 2. myTableAdapter.Update(myDataSet) 3. myBindingSource.EndEdit() After line 1, - myDataSet.HasChanges = true (understandable) After line 2, - myDataSet.HasChanges = false (understandable) After line 3, - myDataSet.HasChanges = true I'm unsure of why this would occur in line 3, shouldn't this be false because I just ran the updates on the dataset?

    Read the article

  • dataset using where condition from another query

    - by refer
    here's my code. I have a dataset that has its values and then i run an independent query which uses the same tables as dataset. now when i run the dataset, i want it to get a where condition on the query result. here's the code - sql = "SELECT ID, name FROM books WITH(NOLOCK) WHERE id =" & Session("ID") ds = FillDataset(sql) Sql1 = "SELECT n.id as id,a.name as title FROM books n WITH(NOLOCK)" & _ "LEFT JOIN new_books a WITH(NOLOCK) ON a.id = n.book_id " rd = ExecuteReader(SqlCnn, SqlStr) Now after this i make an htmltable and all the cells are loaded with the data from datareader(rd). but 1 dropdown is loaded from the dataset. i want that dropdown to have the selectedvalue which is the value from the datareader(rd). how can i do that?

    Read the article

  • Dataset size limit as an xml file.

    - by np
    Hi We are currently using DataSet for loading and saving our data to an xml file using Dataset and there is a good possibility that the size of the xml file could get very huge. Either way we are wondering if there is any limit on the size for an xml file so the Dataset would not run into any issues in the future due to the size of it. Please advise. Thanks N

    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

  • LINQ self referencing query

    - by Chris
    I have the following SQL query: select p1.[id], p1.[useraccountid], p1.[subject], p1.[message], p1.[views], p1.[parentid], case when p2.[created] is null then p1.[created] else p2.[created] end as LastUpdate from forumposts p1 left join ( select parentid, max(created) as [created] from forumposts group by parentid ) p2 on p2.parentid = p1.id where p1.[parentid] is null order by LastUpdate desc Using the following class: public class ForumPost : PersistedObject { public int Views { get; set; } public string Message { get; set; } public string Subject { get; set; } public ForumPost Parent { get; set; } public UserAccount UserAccount { get; set; } public IList<ForumPost> Replies { get; set; } } How would I replicate such a query in LINQ? I've tried several variations, but I seem unable to get the correct join syntax. Is this simply a case of a query that is too complicated for LINQ? Can it be done using nested queries some how? The purpose of the query is to find the most recently updated posts i.e. replying to a post would bump it to the top of the list. Replies are defined by the ParentID column, which is self-referencing.

    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

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