Most voted "linq" questions
Language Integrated Query (LINQ) is a component of Microsoft. NET Framework that adds native data query (query) functionality in . NET languages.
Learn more…578 questions
Sort by count of
-
4
votes1
answer109
viewsRandom Order with Entity Framework
I would like to translate the following SQL statement to an expression lambda: SELECT TOP 1 * FROM tbPessoa order by NEWID() What do I put in OrderBy that will be accepted? var pessoa =…
-
4
votes1
answer119
viewsHow do MVC application authentication with Linux?
I have a project in ASP.Net MVC and I’m putting the authentication manually. Everything is going well, but I used as a reference a ready-made project that uses the Entityframework, but I want to use…
-
4
votes3
answers614
viewsHow to create a custom list using data from four tables?
I have the following class: Nota { int id; int idFornecedor; int idProduto; int idClasse; } and I have the respective classes for the previous class ids: Fornecedor { int id; string descricao; }…
-
4
votes3
answers146
viewsPerformance "Where in foreach vs if"
Which case would perform best? var chaves = new list<string>(); foreach(var item in lista) { if(!string.IsNullOrEmpty(item.Chave)) { chaves.Add(item.Chave); } } Or listaValida = lista.Where(x…
-
4
votes1
answer256
viewsConvert LINQ to Dapper query
I have a LINQ query where I get the complete data. Because of performance, I am converting the query and using Dapper. I have the following entities: public class Cliente { public int ClienteId {…
-
4
votes1
answer216
viewsTranscribe SELECT to LINQ query expression
How can I reproduce the query then to LINQ expression? SELECT nome_empresa, Count(funcionarios.id_funcionario) AS qtdfuncionario, Count(id_colaborador) AS qtdcolaboradores FROM empresas JOIN…
-
4
votes3
answers351
viewsGroup by days interval using Linq
How can I use interval grouping with Linq? var dados = new[] { new { Id = 0, dias=100, preco= 25, Nome="etc"}, new { Id = 1, dias=40, preco= 50, Nome="etc1"}, new { Id = 2, dias=50, preco= 55,…
-
4
votes2
answers71
viewsGet null fields from the database with LINQ
I have a table of Gestor in the database where you store information of a user with Manager profile. In this table, I have two FK's: uniaoId and schoolboy. Well, that manager MUST belong to a union…
-
4
votes2
answers1359
viewsSearch specific value within a file . txt C#
I have a. txt file with the following lines: 000-000 = CRT 001-000 = 00000021 009-000 = 00 012-000 = 247823 013-000 = 0000559877 022-000 = 24082017 023-000 = 152842 032-000 = 80F1 100-000 = JORGE…
-
4
votes0
answers285
viewsService returns me cast error when consumed
I decided to make another post, since the subject is another, although in the original post, in the comments we touched on the subject, but no depth. I have that mistake:…
-
4
votes1
answer1604
viewsSee Date only, in a Datetime field with LINQ
I’m generating a report in an app that I’m developing, but I have a little problem. When sending a query in a date interval, I can’t get anything, because it is a DATETIME (I can’t change to date…
-
4
votes1
answer242
viewsWhat is the difference between Xmldocument and Xelement?
I’d like to know the difference between Xmldocument and Xelement.
-
4
votes2
answers960
viewsWhat is the purpose of the 'Let' statement in a LINQ query?
I have the following LINQ query: var source = from em in query select new { Id = em.UniqueID, Data = em.Data == DateTime.MinValue ? "" : em.Data.Value.ToString("dd/MM/yy HH:mm") }; The estate Data…
-
4
votes1
answer561
viewsMany Relationship Query for Many Entity Framework
I’m new to Entity Framework and Linq, so my doubt may be very simple, but it’s breaking my head. I have two entities: public class Fornecedor { public int FornecedorId { get; set; } public string…
-
4
votes4
answers144
viewsProblems initializing a type within a LINQ query
I am going through the following problem, I am assembling an API for a forum application and this API needs a endpoint returning a collection of Forum who own the property ParentId nulla. Then I…
-
4
votes4
answers156
viewsHow to avoid repetition in LINQ queries?
I have the following query LINQ which is in a method that returns all products: var query = from p in Produtos select new Produto { ProdutoId = p.ProdutoId, Descricao = p.Descricao, Preco = p.Preco,…
-
4
votes2
answers403
viewsHow to filter in LINQ for every X months?
Hello, I would like to know the best way to filter a list of objects using LINQ in C#, I have a list of objects called Measuring, each measurement has a Data property, which is the date that was…
-
4
votes2
answers129
viewsWhat is the difference between LINQ research forms with Datetime.Now?
I am running two code snippets and they are giving different results. Does anyone know why? This code shows coupons only that have the validity of the current date and time + 3h (I don’t know why):…
-
4
votes1
answer3602
viewsLinq Compare two lists of different types
I have two different lists A List<ProdutoTag> and B = List<Tag>: public class ProdutoTag { public Int64 ProdutoId { get; set; } public Int32 TagId { get; set; } public Double Peso { get;…
-
4
votes1
answer58
viewsError using Split inside Select
Why the exception below occurs when using Split within a Select in a IQueryable? The LINQ Expression Node type 'Arrayindex' is not supported in LINQ to Entities. I already managed to solve the…
-
4
votes2
answers842
viewsUsing Array.Foreach to modify the collection
I want to remove spaces from the beginning and end of the string (Trim) in all positions of array, but none of the ways below worked. What am I doing wrong? var optionArray = new string[] { "in the…
-
4
votes1
answer48
viewsError There are no comments for in the schema
I’m following a tutorial to access database via LINQ. In the video, I saw a function that returns me a list with the database data: public static List<LicitacaoOffline> Buscar() {…
-
4
votes2
answers220
viewsHow to map and obtain only one property or field of a query?
I’m using the Dapper that has the purpose of map properties of objects. See a practical example: var servico = conexao.Query<Servico>(statement.ToSql(), new { IdServico = id }).First(); That…
-
4
votes2
answers544
viewsMap Enum with search conditions
I have a class that makes the search conditions as follows: public enum EnumCondicao { [Display(Name = "Igual")] Igual, [Display(Name = "Diferente")] Diferente, [Display(Name = "Maior")] Maior,…
-
4
votes3
answers1052
viewsHow to filter a list type Ienumerable<> through another Ienumerable<>?
How to filter a type list IEnumerable<> passing a parameter of type IEnumerable<> preferably via expression lambda or linq? Based on the filter below I expect this result: {MundoId = 0,…
-
4
votes2
answers227
viewsRemove "OR" condition from LINQ query
I have the following method: bool naoUsarNomeCliente = String.IsNullOrWhiteSpace(filtro.NomeCliente); long codigoExterno; bool naoUsarCodigoExterno = !long.TryParse(filtro.CodigoExterno, out…
-
4
votes3
answers470
viewsLeft Join with LINQ
I have two tables that come from different repositories. One comes from an API and I have one that comes from BD. I already have the two tables mapped to classes. I want to select all records from…
-
4
votes1
answer578
viewsHow to generate a subquery in Line/EF
Hello, everybody. I have a situation, where I concatenate some subquerys Sqls that are concatenated into other Sqls queries, to return some values. I have several functions like these, because I use…
sql-server entity-framework linq linq-to-entities linq-to-sqlasked 5 years, 9 months ago Fabiano Richetti 41 -
4
votes1
answer332
viewsSwitch to lambda/Drum a foreach
I have this method with a foreach inside [Route("")] [HttpGet] [ResponseType(typeof(List<MarkupListResponse>))] public IHttpActionResult Get(int resellerId) { var catalogs =…
-
4
votes2
answers915
viewsSelecting an Item from a List<T> with index equal to the iteration value of for
How can I select an item from a list by the index, this being equal to the iteration value of a for? I tried to accomplish using LINQ, while compiling and inspecting the StringBuilder which would…
-
4
votes2
answers176
viewsDoing a LINQ function that can be called in an EF query
I have the following expression: Where(cd => cd.Modal == modal) .Select(s => s.Volume) .DefaultIfEmpty(0) .Sum() what use to make a same calculation several times within a few querys through…
-
3
votes2
answers408
viewsWhat is the simplest way to recover certain elements of an XML with Linq?
I got the following XML: <clientes> <cliente> <documentos/> <livros> <livro nome="Nome1"/> <livro nome="Nome2"/> </livros> </cliente> <cliente>…
-
3
votes2
answers954
viewsFilter on Where the longest date with LINQ
As I pass the Where of this max datatransaction, ie I wish to bring the result but by the highest date. var resultado = (from ci in webDB.T_Controle_Importacao where ci.CNPJ == cnpj let dd =…
-
3
votes1
answer611
viewsError while passing Adddays in Lambda expression
In this lambda, gives me the error below, when it enters the IF: var resultado = webDB.T_ControleColetor .Where(cn => cn.CNPJ == cnpj) .Where(dt => dt.DataControle == DateTime.Now.AddDays(-1))…
-
3
votes3
answers3330
viewsGrab ID immediately after insertion
Entity and LINQ usage. I would like to know how I get a generated ID right after entering a record, before anyone else can enter it as well, that is, ensure that that ID is the one generated by me.…
-
3
votes1
answer70
viewsName of columns in web service return xml
That line gives me that mistake: if (db.T_TarefaParceiro.Max(p => p.IDTarefaParceiro) != null) The mistake The cast to value type 'System.Int32' failed because the materialized value is null.…
-
3
votes1
answer695
viewsError when calculating date difference in Entity with Linq to Entities
Before I was like this my expression: var resultado = db.T_CRM_StatusPDV .Join(db.T_PDV, t1 => t1.DE_Cnpj, t2 => t2.CNPJ, (t1, t2) => new { t1, t2}) .Where(dt =>…
-
3
votes2
answers103
viewsHow to capture Assembly from classes that inherit from a single class
I have numerous classes. All inherit from a single class public abstract class ClasseBase { public int Id {get;set;} } and other classes: public class Teste1 : ClasseBase{ } public class Teste2 :…
-
3
votes1
answer103
viewsConverting an SQL from Sql Server to C#LINQ
I have an sql that looks like this: SELECT coluna1, coluna2, coluna3 FROM ( SELECT coluna1, coluna2, coluna3, ROW_NUMBER() OVER(ORDER BY coluna1, coluna3 desc) as row FROM tabela1 WHERE coluna4 in…
-
3
votes1
answer1774
viewsHow to group by 2 properties and sum the values
I have no idea how to do this consultation on LINQ. How can I from sales list. Separate the sales per hour, then group the products and add up the quantities sold? public class Venda { public int Id…
-
3
votes1
answer253
viewsHow to convert lambda to Expression Trees format?
How to convert that lambda: Set.Asqueryable(). Where(profile => profile.CostCenters.Select(Costcentre => Costcentre.Id). Any(Id => Ids.Contains(Id))).Tolist() Actually I managed to do even…
-
3
votes1
answer1373
viewsProblem returning Entity models: "The Entity or Complex type ... cannot be constructed in a LINQ to Entities query"
I’m trying to return a list of objects generated by the Entity Framework Database First but I get this error: The Entity or Complex type 'leaosites04Model.TB_LEMBRETES' cannot be constructed in a…
c# entity-framework linq entity-framework-6 linq-to-entitiesasked 10 years, 4 months ago Reynaldo 141 -
3
votes1
answer231
viewsTransforming Query into Linq
I need to turn this query into Linq: select B.Nome from Gestor A inner join Entidade B on A.UniaoEntidadeId = b.EntidadeId group by B.Nome HAVING COUNT(A.EscolaId) > 0…
-
3
votes1
answer743
viewsHow to change a property during a LINQ query?
Is there any way to change in the LINQ query a property of the query itself? Ex.: I’m doing a consultation on a List<Cliente> and I want all customers whose NomeFantasia begin with * have the…
-
3
votes1
answer965
viewsHow to simplify a foreach by a Linq expression - Lambda
Performance is not an issue in my project, I want to know a simpler and readable replacement for my foreach using Linq and Lambda (if possible). // 'DiscoVirtual' é uma classe // 'this.HDs' é um…
-
3
votes1
answer793
viewsLambda Linq Problem: LINQ to Entities does not recognize... get_Item(Int32). How to resolve?
When trying to execute the loop for (time when query is executed) is giving error in my lambda expression: var funcionarios = repository.Funcionarios .Include(x => x.Cargo) .Include(x =>…
-
3
votes1
answer328
viewsReturn Join Linq C#
I’m trying to return a Join to my class and it’s giving me the following error Error 1 Cannot implicitly convert type System.Collections.Generic.List in 'System.Collections.Generic.List' C:…
-
3
votes2
answers94
viewsSimplify LINQ p => p.Tipo.Toupper(). Equals("S") && p.Modo.Toupper(). Equals("S")...,n
How to simplify LINQ expression? p => p.Tipo.ToUpper().Equals("S") && p.Modo.ToUpper().Equals("S")...,n
-
3
votes1
answer77
viewsUse Defaultifempty in a LINQ query with Join
The goal is to join these two list, being that if in the list pr have an item that does not match the list un, the default value will be returned. I know there are other ways, but I would like…
-
3
votes2
answers1101
viewsDistinct in the Plains does not work
I did this Illumination on my model: public static List<MontaArvoreAcao> CriarListaArvoreAcao() { RupturaEntities db = new RupturaEntities(); var _listaUnidade = ( from r in db.Ruptura join a…