FAQ Database Discussion Community


In my model, what element type do I use for a SQL table column of type smalldatetime?

c#,sql,asp.net,asp.net-mvc,linq
I have a table dates with columns fileid of type int and dtime of time smalldatetime. The is meant to keep track of the date and time that a file was uploaded. What should ??? be in the following piece of my model? Should it just be a string, and...

Sort a LINQ with another LINQ in MVC

sql-server,linq,entity-framework,controller
Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

How do I convert this tSQL statement to LINQ using group by in a sub query

c#,sql-server,linq,tsql
I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data. var rv = (from i in DC.TableA select i).ToList(); This is the sql I want to write a C# LINQ query for but...

LINQ: is there a way to conditionally modify expression?

c#,linq
I need to search in my context and child objects for a string. The main objects are 'Property' and 'BayOption' with a property having 1-many BayOptions. The tricky part is, almost each parameter for both objects has an 'XXXXOverride' bool and a complimentary 'XXXXOverrideValue'. I need to check if the...

How to convert to LINQ Queries

c#,linq,foreach
i want to convert the below for loops into a LINQ query. What i am doing is adding the list of values into a dictionary by using for loop. Now i want them to be executed by using LINQ Queries. Can any one help me in doing that as i...

Convert delimited string to array and group using LINQ in C#

c#,arrays,linq,csv
I have a string that has a delimited format like this: orgname: firstname lastname, firstname lastname; (this can repeat with orgnames and variable number of names for each org) Example: **XXX University**: Martha Zander, Rick Anderson; **Albert School**: Nancy Vanderburg, Eric Towson, George Branson; **Hallowed Halls**: Jane Goodall, Ann Crabtree,...

Load XML to list using LINQ [duplicate]

c#,xml,linq
This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

Update list of items in c#

c#,linq,list,updates
I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Dynamic lambda wrapped with try catch

c#,linq,dynamic,lambda
I want to filter an IEnumerable<ModuleItem> by an Where calls defined by the user (so the expression is given by a String object) So far I am able to create my filters with DynamicLinq with this code Expression<Func<ModuleItem, bool>> expr = System.Linq.Dynamic.DynamicExpression.ParseLambda<ModuleItem, bool>(value, null); The problem is that the overall...

Listing directories by content size using C# [closed]

c#,.net,windows,linq
I'm trying to list all folders of my c drive excluding the document folder which i do not seem to have access to. This first seemed rather simple to me but i found myself still struggling with it despite the seemingly rich .net library. I can't post any code as...

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4
I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me. Action Method public class VehicleController : Controller { private readonly IService<Vehicle> _service; public VehicleController(IService<Vehicle> service) { _service = service; } public JsonResult AutoComplete(string term)...

Casting a list of objects to another one

c#,linq,casting,lambda,dao
I have the following classes(entities): Entity(base class, has 3 props) & Category(derives from Entity and adds some other props) The problem occurs when I read data from the DB(the fill method returns a list of Entities) and the compiler doesn't allow me to cast from Entity to Category. The problematic...

Get and add all properties of type Mname from a list of objects and add them dynamically too a drop down

c#,linq,list,object,properties
Ok so I have an object type called monsters and a list of all monsters I need to get all the strings from the property called MName and add each one to a Drop down text box. here is the class so far.(sorry Im really new to coding.) using System;...

Difference between cast and as inside a select in LINQ

c#,linq,entity-framework
This code throws exception: var query = services .SomeQuery(bar).select(x => (Foo)x) .Where(x.PropertyOfFoo == FooState.SomeState); var result = query.ToList(); The exception: Unable to cast the type... LINQ to Entities only supports casting EDM primitive or enumeration types. This code works: var query = services .SomeQuery(bar).select(x => x as Foo) .Where(x.PropertyOfFoo ==...

Find a fixed length string with specific string part in C#

c#,.net,string,linq
I want to find a string of fixed length with specific substring. But I need to do it like we can do in SQL queries. Example: I have strings like - AB012345 AB12345 AB123456 AB1234567 AB98765 AB987654 I want to select strings that have AB at first and 6 characters...

joining two collections in C# or JavaScript

javascript,c#,linq,collections
I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Remove the Parent Node based on Child condition

c#,xml,linq,linq-to-xml
I need help here to remove the xml node based on some condition Here is my xml <result> <product> <auto> <report> <auto> <admin></admin> <report> <search> <subjects> <subject> <name> <first>John</first> <last>D</last> </name> </subject> </subjects> </search> </report> </auto> </report> </auto> <auto> <report> <auto> <admin></admin> <report> <search>...

Linq implementation of for and if loop

c#,linq,loops
This snippet below checks if eCode (an integer) is equal to any element in list1<int> and if yes, it does something. My question is the following.. what would be a linq implementation of this? I'm new to C# and Linq and not sure how to proceed. for (int i =...

sqlite query slow, how to optimize (using linq to entities)

c#,linq,entity-framework,sqlite
I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

Can't access any of Linq methods

linq,asp.net-web-api
I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

LINQ: How to add multiple fields for grouping

c#,linq
this code apply grouping on party name whose ordinal position is 12 group line by line[12] into newGroup now i want to know how to apply group on multiple field whose ordinal position is 0 means line[0] line[0] will have date and time both. i just like to group on...

LINQ pad is showing SUM at end of result

linq,linqpad
When i run the below query by LINQ PAD then saw it was showing sum at the end of result. here is the full code and it is working. void Main() { var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv"); var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // i am assuming that line[7] is the...

Linq in C++ CLI

xml,linq,visual-c++,xpath,c++-cli
I need to get details from a xml file. I wrote code in C# but not able to rewrite in C++/CLI. Code in C# class cROI { public Int16 iX { get; set; } public Int16 iY { get; set; } public Int16 iWidth { get; set; } public Int16...

C# How i use linq with explicit interface attribute?

c#,linq,inheritance,interface,explicit
i have one class with two inheritance interfaces and yours attributes are explicits because both have some equals attributes, so, i need use LINQ with this class, but i can't access the explicits attributes when i use "select new Foo" ... look the case: public class QuestaoMontaProva : IQuestao, IExercicio...

In which cases do I need to create two different extension methods for IEnumerable and IQueryable?

c#,.net,linq,ienumerable,iqueryable
Let's say I need an extension method which selects required properties from the collection. This can be entity or .net collection. So I have defined such extension method: public IQueryable<TResult> SelectDynamic<TResult>( this IQueryable<T> source, ...) This works fine for IQueryables. But, I also need to call this function for IEnumerables....

Check if a List contains specific types (multiple)

c#,linq
I have a block of code that checks a List for derived types and then adds to first instance to another List. var bacon = new List<Bacon>(); // A list of all bacon products var selectedBacon = new List<Bacon>(); var smokey= bacon.FirstOrDefault(x => x is Smokey); if (smokey != null)...

Order LINQ query elements by a collection of numbers

.net,vb.net,linq,compare,compareto
This is a partially defined function that I'm using to retrieve the specified lines of a textfile, by passing the index of the lines I want: Public Shared Function GetLines(ByVal sourceFilepath As String, ByVal lineNumbers As IEnumerable(Of Integer)) As IEnumerable(Of String) Return File.ReadAllLines(sourceFilepath, encoding). Select(Function(line As String, index As Integer)...

LINQ: Searching inside child entities

c#,linq,asp.net-mvc-5
I have 'Property' objects with 'BayOption' child objects. I need the site search to search through the child BayOptions as well as the Properties and return Properties if the search criteria matches the child or parent. A Property can have multiple BayOptions (and usually does). I was unsure if .Select...

orderby () containing numbers and letters

c#,wpf,linq,linq-to-sql,sql-order-by
I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

How to call a lambda using LINQ expression trees in C# / .NET

c#,.net,linq,lambda,expression-trees
I want to use expression trees to dynamically create a method to call a lambda. The following code runs fine for the first call to the ComposeLambda function, but the second call fails with the following error message. Incorrect number of arguments supplied for call to method 'Int32 lambda_method(System.Runtime.CompilerServices.Closure, Int32)'...

How to add empty value from gridview cell to list?

c#,linq,list,datagridview,datagridviewtextboxcell
I want to enter guest details(Title,Firstname,midname lastname) in a list<string> ,the guest details can be empty.I'm using LINQ for inserting in the list.I had referred this question for the LINQ code DataGridView write all values from a column to list All I want to do is enter the text into...

CSV File header part is coming parsing by LINQ

c#,linq,csv
the below way i am parsing csv file by LINQ but i found header part is coming when i inspect user class data. what is wrong there in code. var csvlines = File.ReadAllLines(filename); // IEnumerable<string> var csvLinesData = csvlines.Select(l => l.Split(',').Skip(1).ToArray()); // IEnumerable<string[]> int flag = 0; var users =...

“CLR detected an Invalid Program” when compiling a constructor for List

c#,.net,linq,lambda,clr
I'm running into a strange problem when compiling a lambda expression for a parameterless constructor into a delegate. It works for almost all types that I have tried. Only the List<> is producing a “CLR detected an Invalid Program”. A Collection<> or an inherited class from List<> would not present...

Distinct() How to find unique elements in list of objects

c#,linq,distinct
There is a very simple class: public class LinkInformation { public LinkInformation(string link, string text, string group) { this.Link = link; this.Text = text; this.Group = group; } public string Link { get; set; } public string Text { get; set; } public string Group { get; set; } public...

Convert SQL to linq statement

c#,linq,asp.net-mvc-5
I would like to convert the SQL syntax below to a linq statement to get a single boolean result back. The SQL is checking if a user exists in a current role. select case when exists (select 1 from Global.Application as a join Global.Role as r on a.ID = r.ApplicationId...

Selecting Multiple Linq Fields Removing Column Names

c#,linq,razor
I need to select multiple fields into an enumerator to run a foreach in my Razor web app. In the controller, I have: ... cols = (from b in a.RefTable select new {b.Col1,b.Col2,b.Col3}), ... It returns the values correctly when I use: @foreach(var col in @item.cols) { @col } However,...

Grabbing most recent transaction/record

c#,linq
I'm having trouble creating a linq statement that would grab the most recent transaction that happened before the startdate specified. Was wondering if anyone can help me. For example startdate is January 20st. Id LoanId TransactionDate InterestDate Balance 1 5 January 5 January 3 5000 1 5 January 30 January...

How can I omit NULL values when converting DataRow to a Dictionary in C#?

c#,linq
I am using Newtonsoft.JSON to convert Dictionary objects to JSON, the Dictionary objects are coming from a DataTable object, which I convert to Dictionary in order that I might easily serialize the whole table to JSON. The function that I am using that converts from a DataDictionary looks like this:...

How to declare var datatype in public scope in c#?

c#,linq
I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

Adding where clause to IEnumerable Select

c#,asp.net-mvc,linq
I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

Database error in web api

c#,sql,linq,asp.net-web-api,odata
I am trying to create an odata endpoint for a table valued function in sql database. I get the exception: The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. I am sure with my code and unable to...

Updating entity framework model using Linq

c#,sql,linq,entity-framework
I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

Group by day, time and id in one LINQ

c#,linq
I have a list of Example class elements: public class Example { public long Id { get; set; } public string Name { get; set; } public DateTime SomeDate { get; set; } } Now I want to group it using ONE LINQ to make the following hierarchy: public class...

Count number of occurrences of each month in db table asp.net linq

c#,asp.net,linq,sql-server-2008
I have a table which contains a date col. I want to use LINQ query and count the occurrence of each month and display it like month, occurrence of month in the table 1=2(1 is month, 2 is number of occurrence),2=5,3=12 and so on using asp.net. Can somebody please tell...

ForEachAsyc with Result

c#,linq,task-parallel-library,task
I'm trying to change Stephen Toub's ForEachAsync<T> extension method into an extension which returns a result... Stephen's extension: public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current); })); } My approach...

Get parameters outside of Grouping Linq

c#,.net,winforms,linq
I need to get some Field's out of the Group using linq for example, this is my code: (from PaymentTypes in PaymentTypes_DataTable.AsEnumerable() join CashTransactions in CashTransactions_DataTable.AsEnumerable() on PaymentTypes.Field<Int32>("cashpaymenttype_id") equals CashTransactions.Field<Int32>("cashpaymenttype_id") into JoinedCashTransactions from CashTransactions in JoinedCashTransactions.DefaultIfEmpty() group CashTransactions by PaymentTypes.Field<Int32>("cashpaymenttype_id") into GroupPaymentTypes select new {...

Issue displaying LINQ query results in a grid in C#

c#,linq
I received some help here with the following LINQ query, but am still struggling with it. The result I'm trying to obtain is to display some attributes and their values from an xml file in a DataGridView control. I'm calling my method from a button click and am trying to...

Compare if the characters in a string are a subset of a second string in C#

c#,linq,string-comparison
I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example: "met".IsContainedWithin("meet"); => true "meet".IsContainedWithin("met"); => false A multi-set would be nice but...

Linq where clause with if condition

c#,linq
I have the following model: class Project{ bool IsDeleted {set;get;} ICollection<Document> Documents {set;get;} } class Document{ Project Project {set;get;} int? ProjectId {set;get;} } I am querying Document repository, I want to get all the documents and also the documents whose project is not deleted. var documents = _repository.Include(p=>p.Project) .Where(m =>...

Search functionality across many columns

c#,asp.net-mvc,linq
I need to make a search for a new website I am building. Some of the columns I need to search are int and some are string. public ActionResult Index(string id) { if (!String.IsNullOrEmpty(id)) { var results = db.Properties.Where(x => x.Address.Contains(id) || x.Address2.Contains(id) || x.City.Contains(id) || x.Description.Contains(id) || x.GrossLeasableArea.Contains(id) <--...

How can I select items where there exists a reference between each item and all items in a list?

c#,linq
I have a list of objects called Keywords, each with an Id. In my database, I have a table of Forms and a table of KeywordReferences. Each KeywordReference has a FormId and a KeywordId. What I need to do is create a query that gets all Forms where there exists...

Please help me convert this sql to LINQ

linq
DECLARE @items table ( pfid varchar(8), timestart datetime, timeend datetime ) insert INTO @items(pfid,timestart,timeend) VALUES('123456','12:00 AM','3:00 AM') ,('987654', '2:00 AM', '4:00 PM') ,('492384', '3:00 PM', '9:00 PM') SELECT * FROM @items a INNER JOIN @items b ON a.timestart < b.timeend AND b.timestart < a.timeend AND a.pfid != b.pfid I need...

nested IN subquery in linq to sql

sql,linq,linq-to-sql
confused how to write this sql query into linq to sql select FirstName from [User] where [UserId] in( select LenderId from AffiliateLenderRelation where AffiliateId in (select Userid From [User] where [UserId] = 11) ) what i have tried so far var innerquery = from iq in db.AffiliateLenderRelations where iq.AffiliateId ==...

VB LINQ - Take one random row from each group

vb.net,linq,random
I'm trying to get one random row from each group of rows. I'm trying to use LINQ, but I'm not sure if that's the right approach. I'd like a Dictionary of Key/Name pairs. My table is as such: AnswerGroup AnswerKey AnswerName --------------------------------------------- 1 1 Yes 1 2 No 2 1...

Convert DataTable into object[ , ] array with LINQ

c#,linq,datatable
I sincerely apologize if this has been asked before; maybe I am just blind and not finding it. Is it possible to convert a DataTable into an object[ , ] type array using LINQ? Using the following code I can convert it into object[][] but that's not what I need...

Sorting a dictionary value which is a list of objects by given fields

c#,linq,sorting,dictionary
I have a SortedDictionary whose value is a List of objects. I want to sort the value(the list) of each key by a given property of the object. In the current situation, I need to sort the list first by objects's lastname, then by firstname. I tried LINQ and it...

How to write Nested LINQ for specific scenario

c#,linq
Apologized to post a problem for which i could not construct anything solid. it is very shameful for me to post like this kind of question even after having so high reputation for this web site. Most of the time i write sql in store procedure in sql server and...

LINQ to Entities Retrieving related Entities or T-SQL

c#,sql-server,linq
I have these (simplified) models: class Vendor { public int Id { get; set; } public IEnumerable<Product> Products { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Show { public int Id { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Booth...

check if a list contains all the element in an array using linq

vb.net,linq
I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

Get a single text value using linq

c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3
I am using this line to return a value, but instead its getting a True var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First(); This the view data passes from the controller var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"]; public ActionResult Edit(int? id) { var listFields = from b in db.Propiedades where b.Entidad.Nombre ==...

Sort Array by contains specific char count

c#,linq
I have an array and I want to sort this array by its element' specific character count. var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length); but this does not work at all. How can I provide the LINQ code for this problem ? myArray[0] = "word1 word2" myArray[1] = "word1" myArray[2]...

Improve my SQL Select statement to select students who have not fully completed a section

sql,sql-server,linq,tsql
My SQL skills are quite limited. I'm in my second year of computer science at a technical college. I'm building a windows forms application that will allow the BAS director at my college to keep track of students and their progress throughout the courses. I have complete control over the...

Linq Conditional DefaultIfEmpty query filter

c#,linq,asp.net-mvc-5,linq-query-syntax
I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

C# lambda expressions without variable / parameter declaration?

c#,.net,linq,lambda
What's it called when a method that takes a lambda expression as the parameter, such as Enumerable.Where, is invoked without actually declaring a variable or method parameter in the expression? For example, I'm familiar with this lambda expression syntax: public string GetDigits(string input) { return new String(input.Where(i => Char.IsDigit(i)).ToArray()); }...

WPF, DataGrid, clicked item/row does not highlight (blue background)

c#,wpf,linq,datagrid
Here is the DataGrid XAML: <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Height="501" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridTrades" VerticalAlignment="Top" Width="574" SelectionChanged="dataGridTrades_SelectionChanged"> <DataGrid.Columns> <DataGridTextColumn Header="ID" Binding="{Binding TradeID}" IsReadOnly="true"/> <DataGridTextColumn Header="Account" Binding="{Binding AccountName}" IsReadOnly="true"/> <DataGridTextColumn Header="Card Name" Binding="{Binding...

ExecuteQuery returns empty collection when there is only a single result

c#,sql-server,linq
I'm using a auto created Linq to SQL Classes dbml and I have created the model class by hand. It should select all Schemas from a SQL Server, which is working when there are more than one Schema in the Database, but when there is only a single result I...

How to select rows from a DataTable where a Column value is within a List?

asp.net,.net,vb.net,linq,datatable
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this: SELECT * FROM MyTable WHERE uid IN (123, 456, 789) That's effectively what I want to do with a...

How to select all objects that have a property value in list of values?

c#,linq,linq-to-entities
I have a table named Items. Items have a property named "locationId" Given a list of location Ids, how do I select all items? List example List<long> locationIds = new List<long> { 1, 2, 3 }; Essentially the query below, but for multiple locations at once: var sleectedItems= db.Items.Select(i =>...

Error when building an XDocument

c#,xml,linq,xpath,linq-to-xml
Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Using Linq to get XML data from database

c#,xml,linq,linq-to-xml
I'm struggling to get the values of a single xml node using Linq. Here is my XML. <?xml version="1.0" encoding="utf-8"?> <record> <AddressLine1>abcd street</AddressLine1> <AddressLine2>xyz AVE</AddressLine2> <AddressCity>Illinois</AddressCity> <AddressState>Chicago</AddressState> <AddressZip>23434</AddressZip> </record> And here is my c# code XElement xmlDoc = XElement.Parse(varQ.Content); //When I debug I find that xmlDoc contains the XML. So...

Add children to XElement via LINQ

c#,xml,linq
I have a Collection of a class that looks like: public class Group { public string Name { get; set; } } private ObservableCollection<Group> _groups; now I want to create a xml structure from groups that looks like: <Ou> <Group>AAA</Group> <Group>BBB</Group> <Group>CCC</Group> <Group>DDD</Group> </Ou> I have try following: new XElement("Ou",...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface
I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

How to assign key and count to two different labels asp.net

asp.net,linq
I have this query: var months = dates.GroupBy( x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count()}); lbl1.Text = string.Join(",", months); How do I assign key and count to two different labels?...

Distinct all columns in a datatable and store to another datatable with LINQ

c#,linq
I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but...

Asp.Net Identity find users not in role

asp.net,linq,entity-framework,asp.net-identity
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

LINQ Group By and not contains usage issue

c#,linq
i like to eliminate those user data which start with VM & Voice Mail var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv"); var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); var groupOfUser = from line in csvLinesData where !line[12].contains('VM') and !line[12].contains('Voice Mail') group line by line[12] into newGroup orderby newGroup.Key select newGroup; this line where !line[12].contains('VM')...

DbSortClause expressions must have a type that is order comparable. Parameter name: key

c#,linq
I'm trying to sort a list of names in alphabetical order. I thought that I would be able to do it on my LINQ statement but this didn't turn out the case and it brought me an error. Does anybody know why this is the case and how to fix...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework
I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

LINQ Operator '==' cannot be applied to operands of type 'char' and 'string'

c#,linq
i hardly use LINQ. when today try to compose little one then i am getting error when i try to run my linq query by linqpad. the error is Operator '==' cannot be applied to operands of type 'char' and 'string' void Main() { var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv"); var csvLinesData...

C# Refactoring gigantic switch statement for ordering with LINQ

c#,asp.net-mvc,linq,dry
My problem is repetitive code: a not so DRY switch statement. So I have a table with 12 columns that can be ordered by descending or ascending on click. My current solution is the use of a switch statement that checks which column was clicked. The sortable properties: This is...

Why does .Where() with a Func parameter executes the query?

c#,oracle,linq,entity-framework
Here's how my DataAccessLayer works : public Foo GetFooBy(Func<Foo, bool> filter) { var query = from item in this.DataService.FooSet select item; var where = query.Where(filter); var first = where.First(); return first; } I assumed the query would be run when First() is called but it's actually executed by the Where()....

Dividing an Expression in C# using Expression.AndAlso() causes an Exception

c#,linq,lambda,expression
On my project written in C#, I've found a HUGE predicate that is used in this method of linq : public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); this predicate works perfectly, but it as so much condition that I struggled a lot before understanding it. I would like...

Linq to XML select descendent of descendant each with specific attribute

c#,xml,linq
I have found many articles on getting a descendant with a specific attribute, but I can't seem to find anything on selecting multiple descendants with different attributes with LINQ to XML. So from the following example, I need to select all the Grandchildren where Parent name = Ken AND Child...

C# + linq(concat) rewrite to java

java,c#,linq,java-8
I have a code example in C# (with linq) but am trying to translate this to java code (java 8). But am getting very confused about what happens. Also i am not able to reproduce the same result in java as from the c# code. public IEnumerable<Node> GetNeighborNodes(Node v) {...

Using Linq with VB.NET

vb.net,linq
I am so sorry for asking such a thick question. I need to sort the characters in a string using vb.net. I normally use C#. This is my code: Dim val1() As Char = txtInput.Text.Trim.ToArray val1 = val1.OrderBy(c >= c).ToArray() Tells me that 'c' is not declared. I have imported...

“Left XOR” between two lists with LINQ

c#,linq,ienumerable
I have to collections: IEnumerable<lineResult> diplayedBondsList and List<string> pIsinList lineResult is a very simple class defined as: public class lineResult { public string isin { get ; set ; } public double rate { get ; set ; } public string issuer { get ; set ; } } I...

Finding an item in a list in c#

c#,linq
The code below contains a foreach loop that loops through a list of string collection which contains XML. While enumerating through the collection, it reads the question and answer elements and adds them to the list collection. I need to ensure that no repeated question is added to the list...

Passing conditional parameters to Database.SqlQuery

c#,sql,linq,entity-framework
I have been doing the following to pass parameters with my sql query: var retval = context.MyObject.SqlQuery(sql.ToString(), new SqlParameter("@ProductId", productId), new SqlParameter("@CustomerId", customerId)).ToList(); I ran into a scenario where @CustomerId will not always be used in my sql string. Meaning I used an if statement to either add (Where p.CustomerId...

How To optimise following linq to object query

c#,asp.net,linq,linq-to-objects
I have a enumarable class having following property Sku Itemid colorid size_id eg: sku1 item1 color1 size1 sku1 item2 color2 size1 sku2 item2 color3 size1 here sku can be repeated multiple times I want to change the structure to something like that Sku1 comma_seperated_colors comma_seperated_size so for sku1 the output...

Linq query in C#

c#,linq
I have some xml <?xml version="1.0" encoding="utf-8" ?> <carLot> <vehicle> <vehicleType>Car</vehicleType> <color>Red</color> <transmissionType>Automatic</transmissionType> </vehicle> <vehicle> <vehicleType>Truck</vehicleType> <color>Black</color> <transmissionType>Automatic</transmissionType> </vehicle> <vehicle> <vehicleType>Car</vehicleType> <color>Blue</color>...

Linq join and order by

c#,sql,linq
I have files in one table and file actions in another. I want to get the most recent file that Jeff has taken action on that has a status of 4. In SQL, that looks like this: SELECT TOP 1 files.* FROM files LEFT OUTER JOIN fileActions ON files.FileId =...

Select XML Elements after last matching Element

c#,xml,linq
I have XML file that looks like: <Meal> <MealName>Lunch</MealName> <MealData>blahblahblah</MealData> <MealTime>2015-03-12</MealTime> </Meal> <Meal> <MealName>Dinner</MealName> <MealData>lolololol</MealData> <MealTime>2015-04-27</MealTime> </Meal> I'd like to select MealName and MealData of the last Meal instance. I can do everything else I need with simple LINQ queries just fine. For example, to get data from last week's...

Linq update with specific select of column being null

c#,linq
I wanted to select few columns from SQl and then update that table. I used var xyz_repl= from mfrepl in xyz_repl_alias where (mfrepl.RPT_ID == sched_data.NOTIF_RPT_ID) && (mfrepl.NOTIF_ID == "" || mfrepl.NOTIF_ID == null) select mfrepl; This did my job but then it does not work if any column is NULL.Then...

Using LINQ to reference XML local Xelements

c#,xml,linq
All, It's easy enough to do reference the LocalName of an Element when using a foreach. However, if I'm interested in a particular element name, perhaps because each element has an array of children elements and I want a LocalName of a parental element, how do I go about it,...

how to parse a rgbColor using c#

c#,linq
I am having trouble parsing a RGB color. I need the int values in there own variable. here is a screenshot of what the object looks like I need to end up with this data [0] R = int value G = int value B = int value Name =...

get string array from another delimited string array

c#,arrays,string,linq
I have a string array like below that contains string followed by delimiter(:) and a number. "string:1" "string:1" "string:2" "string:3" "string:5" "string:777" ... i want string array that gets the number from the last delimiter (:) "1" "1" "2" "3" "5" "777" I was wanting to know if i can...

how can I add a column to IQueryable object and modify its values

c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

LINQ to SQL: How to create something like conditional include?

.net,linq,entity-framework,include,condition
I'd like to create a query contains User whose entities has Event with type == 1. I would also like the Event entries loaded into EventsCollection. My code would be something like .Include(u => u.EventsCollection), but this only loads all Event entries - I want to load only with type...

Removing items from an IEnumerable which match items in a List using LINQ

c#,linq
I have a method that returns an IEnumerable of this type: public class ProductUpdate { public string ProductId { get; set; } public DateTime DueDateTime { get; set; } } and I have a List<string> which has a list of dates as strings. What I am trying to do is...

Join 2 tables with multiple references in LINQ

c#,linq,linq-to-sql
I have 2 tables, Table1 and Table2. **Table1** Id Name ------------ 14443 Michael 55658 Brian 84321 Lisa 335896 NULL 1035 Maya 5221296 Brenda **Table2** Id1 Id2 MatchLevel -------------------------- 14443 5221296 0,5192 14443 84321 0,8647 14443 182347 0,6897 **1035 14443** 0,9999 14443 4572311 0,8569 63547 14443 0,9563 335896 14443 0,9418 14443...