Questions tagged [linq]

43427 questions
0

votes
2

answer
34

Views

How to update a global variable inside `where` clause in LINQ?

I want to filter a list using LINQ with Where extension method. But apart from filtering I also want to update a global variable inside Where. However I cannot do it. Consider this example: var list = new List { '1', '2', '3', '4', '5' }; bool flag = false; var newList = list.Where(item => { flag =...
0

votes
0

answer
26

Views

C# Linq questions on select parameters

I have the basic understanding of select method in linq. var arrayIndex = Enumerable.Range(10, 10).ToArray(); This one will create an array with integers 10 to 19. For some real life problems, I need to use the index of the original data. After some research, I found that I can do something like thi...
Will
1

votes
0

answer
9

Views

How can change a MYSQL Join Query in Linq Methods

I write a MySql join code, and want to retrive same value from the Dotnetcore linq methods. My Join code is below: SELECT GL.Id AS GradeLevels, CRS.Name AS CourseName, GL.Title AS GradlevelName, AVG (ASTSTU.ObtainedMarks) FROM GradeLevels GL INNER JOIN Courses AS CRS ON CRS.GradeLevelsID = GL.Id IN...
Vipin Jha
1

votes
2

answer
555

Views

C# Create Lambda Expression Dynamically

I work with Dapper and I try to create auto-mapped method for inner join. This is the example of the models: public class User { public long IdUser { get; set; } public string Email { get; set; } } public class Page { public long Id { get; set; } public string Name { get; set; } public long IdUserC...
Fabrizio Pairone
0

votes
0

answer
6

Views

Linq, EF Core - group by on one field and use other field to get list of data from other table

Can someone help me. I tried everything, nothing worked. I have data in this format table1 Id T_Id 4 2 6 5 6 7 table2 T_Id fname lname 2 mary smith 5 john pope 7 steve blair I want to get data in following format using linq query with EF Core. [{ 'Id' : '4', 'users':[{ 'T_I...
Shamal
1

votes
1

answer
40

Views

Allow only single type of mark in string

I'm trying to figure out, how to allow only single type of mark in string. For example if string inputStr contains different marks: string inputStr = 'hello, how are you? ~ say something: what's up? hi... tell me. what?! ok: so,'; this way: string outputStr = Regex.Replace(inputStr, @'[^\w\s]', '');...
sam324
1

votes
2

answer
49

Views

How to prevent NHibernate SqlDateTime overflow when querying the database without using an IUserType?

Is it possible to prevent this exception when doing an NHibernate Linq query like the following: var dateFilter = DateTime.Parse('1500-01-01'); return _session.Query().Where(l => l.Date > dateFilter).ToList(); Result: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59...
Martin D.
1

votes
1

answer
19

Views

Prevent number from being converted to Scientifc Notation in linq-to-sql

I have a query that fetches data from the database. I have a DTO that contains a property Price of type string. var query = (from Users in _db.Users join pricing in _db.Prices select new { Username = Users.Name, Price = pricing.Currency + ' ' + pricing.Amount } ).AsEnumerable().Select(x => new Use...
crazydev
1

votes
1

answer
48

Views

read xml file having namespace in root

I am trying to get the values of each element from the XML file having namespace in root element but no luck. The xml file looks like I have written some C# code using linq but could not get any result. XDocument xdoc = new XDocument(); var doc = XDocument.Load(fileFullPath); XNamespace ns = 'http:/...
User
1

votes
2

answer
128

Views

Get nested data and sharp into DTO with nested DTO

I'm newbie to EF, Linq and C# in general, I'm stuck with developing following. I cannot map data into structure like this: Id, Actions [ Action1, Action2, Action3 ] I have 2 DTO classes like this: public class TestDTO { public int TestId { get; set; } public TestDTO2[] Actions { get; set; } } and p...
1

votes
1

answer
19

Views

Trying to create a tree of nodes with LINQ to SQL produces NotSupportedException

I have the following code that works perfectly inside LINQPad as you can see in the screenshot. Please, notice the Results part in the bottom part of the screen, where the tree of nodes is shown: But when I run it in my application, it shows the following exception: System.NotSupportedException Unab...
SuperJMN
1

votes
3

answer
79

Views

Why Does ToList throw an Exception when only 1 record is returned

I have a lambda expression that finds all of the labels on a form that contain the name of a particular method (labels are created dynamically and contain a prefix and the method name). The expression removes the prefix and evaluates whether what is left matches the method name. All was working fi...
Rani Radcliff
1

votes
2

answer
45

Views

How can I move on column data to another column in the same row using linq

I am working an an old project which has to do with invoices. My problem is that the previous programmer put some values in the wrong column. To be more specific he put the total amount in column 'credit' instead of column 'charge'. I want to fix those values andmove them to the correct column using...
rippergr
1

votes
1

answer
27

Views

Problem with Convert.ToInt32 and getting error Index and length must refer to a location within the string

We want get crc code from a string. for example: string is (ff03c1) and crc code is (3d). The bellow code works correctly until the string is less than 186 characters. sample string: 20000F38080000D1080020110800190D0000000000000000000000000000000020000F38080000D1080020110800190D00000000000000000000...
mk128
0

votes
1

answer
13

Views

LINQ with Include and Where not showing desired results

I have a linq statement that combines Residents and Requests table like so var resident = await _context.Resident .Include(s => s.Requests) .FirstOrDefaultAsync(m => m.ID == id); The problem is that all requests show up even those that are not related to the Resident. I have tried ad...
Podge Dimagiba
5

votes
3

answer
117

Views

Discards inside C# Linq queries

I wonder if that's good pattern to use Discards in Linq queries according to https://docs.microsoft.com/en-us/dotnet/csharp/discards, example: public bool HasRedProduct => Products.Any(_=>_.IsRed == true); What's pros / cons instead using public bool HasRedProduct => Products.Any(x=>x.IsRed == true...
boski
0

votes
0

answer
12

Views

Compare 2 List - LINQ

There are 2 large list of objects, where I need to do a where clause and find the matching records. List a= ...; List b = ...; A model Id Name Age Address I need to return a list that contains all the object of List after comparing with List. The properties I should check is : If the Ids are equal...
sharon Hwk
0

votes
2

answer
52

Views

how to check the value for null in linq?

I have a table called specifications and a list field whichs values need to be checked for null. Here is the list: List fieldList = new List() { name1, name2, name3 }; //name of the fields I already tried the following: var checkForNull = TableInfo.Get('specifications').Fields.Where(i => fieldList.F...
Evgeniy Bojenov
1

votes
1

answer
575

Views

Getting Xelement.elements() using a path

I have some xml like this. I have the parent element to call .Elements on. I looked this up, but I cant figure out how to do get the element Pr directly XElement element = (from item in parentElement.Elements('Map/Pr') select item).FirstOrDefault(); Path I provided seems to be incorrect. Whats the r...
user3606175
1

votes
1

answer
1.1k

Views

What's the correct way to use Effort with Entity Framework 6?

I'm trying to get some test code working using the Effort data provider with Entity Framework 6. What I'm trying to do seems like it should be the absolute simplest use-case, but I'm just not able to get things to work. Here is my DbContext class: public class CcdReductionFrameCatalogue : DbContex...
Tim Long
1

votes
2

answer
1.9k

Views

Get XElements List of XElements List from XML document using linq to xml

I create a list of node object: public class Node { public string Key { get; set; } public string Value { get; set; } } public class ListNode : List { } And i have an xml document : xxx 111 yyy 222 zzz 333 aaa 444 what i want to do is to put these xml elements to a List of ListNode objects using li...
YouneL
1

votes
1

answer
368

Views

Grouping List elements and map to new model using Linq

I have list of items that should be converted to another data structure using Linq statements. I am able to group list, however, I cannot correctly create subelements. Here is my result model (simplified): public class MyModel { string Name {get; set;} List Submodels {get;set;} } public class MySub...
renathy
1

votes
2

answer
2.1k

Views

C# Remove all Items from List<T> if a property is in a List<string> [duplicate]

This question already has an answer here: C# List.RemoveAll() - How to remove a subset of the list? 1 answer I have a List where T has a string property let's call it Value Then I have a List that contains some keywords. How can I remove all items from the List where the property Value matches one...
user2818430
1

votes
1

answer
3.7k

Views

How to fix 'No property or field exists in type' error?

I got this error when trying to sort any columns that are not in the Order table, if I use OrderBy('Customer.CompanyName' + ' ' + sortDir) the error will gone but all the columns will become unable to sort. The OrderBy method used below come from here. What is the cause of the problem ? public Acti...
Phantom
1

votes
3

answer
456

Views

Get results matching a list of Ids using Linq

I am trying to get the list of gameIds that satisfy all the genreIds included in a a List. The tables (partial): editorial_list: game_id content game_genres (game can belong to several genres): id game_id genre_id I need to get the list of the game Ids of games that exists for all the genre_id's in...
Idan Shechter
1

votes
2

answer
5.3k

Views

LINQ Select Syntaxt VB.NET

I have a list of Tuples I am trying to run a Select and Where query on to return a list of Objects from the Tuple.Item5 parameter. In my where clause I am looking to match Tuple.Item4 to a local variable. I'm not sure what the VB.NET syntax is for the Select portion, I only know the c# syntax. Esse...
Belgin Fish
1

votes
1

answer
93

Views

EF Core dynamic filter

I've been working in a Dynamic filter class for EF Core queries using Expression trees, everything looks good, filter is working, I can pass a filter collection and it works, but when I look at the SQL sentence, it is querying the whole table and applying the filter on the resulting collection, here...
Mauricio Atanache
1

votes
4

answer
66

Views

Using linq to find any of multiple values of List<List<string>>

My list looks like: List. I need to check if any of the nested list first value is equal to some values. This is what I did and it working: if (myList.Any(sb => sb.First() == 'Value1' || sb.First() == 'Value2' || sb.First() == 'Value3' || sb.First() == 'Value4')) I was wondering if there is a wa...
Shahar Shokrani
1

votes
2

answer
57

Views

Linq Include and Where conditions on Parent-child relation

This is my scenerio: I have model of Company: public class Company { [Key] public int Id { get; set; } public string Name { get; set; } public virtual List Products { get; set; } public virtual List Employees { get; set; } } and API endpoint that looks like this: //GET: api/company/Profile?id...
michasaucer
1

votes
1

answer
32

Views

How to generate a dynamic number of ThenBy clauses in a Specification

I'm building a Spec Evaluator which must consider multiple possible OrderBy, as in the next example: if (spec.Order != null) { var count = spec.Order.Count; if (count == 1) { query = query.OrderBy(spec.Order[0]); } else if (count == 2) { query = query.OrderBy(spec.Order[0]) .ThenBy(spec.Order[1]); }...
Erre Efe
1

votes
4

answer
77

Views

Using LINQ to populate a string with a single column value

I'm a newbie both to C# and to LINQ and would appreciate a small push in the right direction. Firstly, I have an Overrides SQL table (and a corresponding EF DB context), which has a Type, Value, and Override Value. The idea is that for a particular kind ('Type') of override, the code can check a pa...
j. kiel
1

votes
2

answer
87

Views

LINQ Except sends first collection's items to IEqualityComparer Equals method [duplicate]

This question already has an answer here: Except has similar effect to Distinct? 2 answers I'm trying to implement IEqualityComparer in order to use Except with complex typed collections. I've encountered with a strange (or a usual thing that I don't know) issue while debugging. I have two collecti...
Kerem Kambur
1

votes
1

answer
60

Views

Linq to SQL check for null on object before accessing property

In simple words, Is there a better way for my code? (check code below). Detail: In LINQ to SQL, I have a query that contains some inner query. In that inner query i used FirstOrDefault() so now i want to check if FirstOrDefault() returned any null value then i can access property. var Bills = db.B...
Ashran Haider
1

votes
1

answer
59

Views

How do I sort a list based on its child object attributes?

I'm wondering if someone can elucidate a method to sort a list of objects based on a child object's attribute. I'm working with the following model: public class Content { public string Id { get; set; } public List Attributes { get; set; } } public class ContentAttribute { public string Value { get...
Not_Sure
1

votes
1

answer
60

Views

Why would one define a local function in C# just to call it right away (in context of IEnumerable<T>) [duplicate]

This question already has an answer here: Meaning of the syntax: return _(); IEnumerable _() [duplicate] 1 answer I had a look at the implementation of several extension methods of the genious MoreLINQ- project. And I came across a style habit that I cannot explain. Maybe some of you can? It happen...
Robetto
1

votes
3

answer
46

Views

Searching records in database by list of Ids

I have a list of ids (itemID's) which I pass to the query like following: using (var ctx = new MyEntities()) { ctx.Configuration.LazyLoadingEnabled = false; ctx.Configuration.AutoDetectChangesEnabled = false; ctx.Configuration.ValidateOnSaveEnabled = false; ctx.Configuration.ProxyCreationEnabled = f...
User987
1

votes
1

answer
46

Views

How to find keys in a Dict<int,List<Tuple<string,string>>> such that the list contains elements with given Item1 and Items

I have a Dictionary L and I want to find in it all keys such that the corresponding value, a List, has tuples such that Item1 and Item2 are equal to some given values 'toto' and 'tata'. I tried like below: var res = L.Where(x => x.Value.ToList().Where(y => y.Item1 == 'toto' && (string) y.Item2 == '...
11house
1

votes
4

answer
57

Views

Abbreviating the string given in a list

I have a list of Names which I want to abbreviate, but I want to know whether an inbuilt function exists for this. eg: John Doe -> JD Jane -> J I am trying something along the lines of this: myListOfNames.ForEach(x => x = abbreviate(x)); I know I can create my own function to do the abbreviations,...
Omkar
1

votes
1

answer
31

Views

Remove From Duplicate Starting Names From List Linq

I have a list of paths that look like //servername/d$/directory I am getting the serverName from the path with the following var host = somePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); I want to refine this list to only 1 server Name listed (say the first one...
nlstack01
1

votes
3

answer
29

Views

using linq on active directories underlying object

Currently my code is: using (var context = new PrincipalContext(ContextType.Domain, adDomain)) { using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) { foreach (Principal result in searcher.FindAll()) { DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry; if (en...
Bryan Dellinger

View additional questions