Menu
  • HOME
  • TAGS

Sort a LINQ with another LINQ in MVC

sql-server,linq,entity-framework,controller

Try this: var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber).FirstOrDefault(); var query = from r in db.SQLViewFinalTable where r.MaterialNumber == materialnumb select r But I can not get whay are you filtering by 80254842 and selecting the same value? You can do directly: var query...

C# + linq(concat) rewrite to java

java,c#,linq,java-8

var q = (from edge in this.Edges where edge.Start == v select edge.End) .Concat(from edge in this.Edges where edge.End == v select edge.Start); this is same as var q = ctx.Edges.Where(o => o.Start == v).Select(o => o.End).Union( ctx.Edges.Where(o => o.End == v).Select(o => o.Start)).ToList(); and this would be Stream<Node> q...

Adding where clause to IEnumerable Select

c#,asp.net-mvc,linq

Per Discosultan in the comments: IEnumerable<int> interestIds = viewModel.ExistingInterests.Where(x => x.selected == true).Select(x => x.InterestId); ...

Database error in web api

c#,sql,linq,asp.net-web-api,odata

It's a common error and there is probably some bug in the ADO.NET EF . In my case the error occurred when the edmx model generated had one of the entities listed in upper case, which in the database is listed in lower case. Strange error to find. I modified...

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

c#,arrays,linq,csv

public static void Main() { var input = @"**Albert School**: George Branson, Eric Towson, Nancy Vanderburg; **Hallowed Halls**: Ann Crabtree, Jane Goodall, Rick Grey, Tammy Hudson; **XXX University**: Rick Anderson, Martha Zander;"; var universities = input .Split(';') .Select(ParseUniversity) .ToArray(); } public static University ParseUniversity(string line) { var split = line...

Difference between cast and as inside a select in LINQ

c#,linq,entity-framework

LINQ to Entities is not the same as LINQ to Objects. While LINQ to Objects functions can take any matching delegate and blindly invoke it as normal C# code, LINQ to Entities treats your lambdas as expression trees because it needs to understand the semantics of those lambdas (not just...

Selecting Multiple Linq Fields Removing Column Names

c#,linq,razor

What you are seeing is the string representation of the object you asked the view to render. You'll need to render each value separately to get your desired output. @foreach(var col in item.cols) { if (!string.IsNullOrEmpty(col.Col1)) { <div>@col.Col1</div> } if (!string.IsNullOrEmpty(col.Col2)) { <div>@col.Col2</div> } if (!string.IsNullOrEmpty(col.Col3)) { <div>@col.Col3</div> } }...

how to parse a rgbColor using c#

c#,linq

Easily accomplished with Regex: string colorStr = "rgb(67,134,215)"; Regex regex = new Regex(@"rgb\((?<r>\d{1,3}),(?<g>\d{1,3}),(?<b>\d{1,3})\)"); Match match = regex.Match(colorStr); if (match.Success) { int r = int.Parse(match.Groups["r"].Value); int g = int.Parse(match.Groups["g"].Value); int b = int.Parse(match.Groups["b"].Value); //// Create your new object with the r, g, b values } ...

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

In a foreach loop the type of your loop variable is the type of the items in the collection, so you want: foreach (Monster m in monsterObjectList) ddlMonsters.Items.Add(new ListItem(m.MonsterName)); You could also bind the list as the data source: ddlMonsters.DataSource = monsterObjectList; ddlMonsters.DataTextField = "MonsterName"; ddlMonsters.DataBind(); ...

Error when building an XDocument

c#,xml,linq,xpath,linq-to-xml

You can ignore pretty much all your code, the issue is just this: XDocument people = new XDocument("Persons"); You can't create an XDocument containing a string, you need to add an element: XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpathFilterDups))); ...

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

c#,linq

Declare it as a known type (not an anonymous type), like this for example: Dictionary<int, string> results = new Dictionary<int, string>(); Then you could store the results in the Dictionary: results = behzad.GAPERTitles.ToDictionary(x => x.id, x => x.gaptitle); And reference it later: private void button1_Click(object sender, EventArgs e) { //...

Convert DataTable into object[ , ] array with LINQ

c#,linq,datatable

You cannot use Linq to create a rectangular array - Linq only operates on single-dimension arrays. You will need to use traditional for loops: object[,] objectArray = new object[dtReportData.Rows.Count, dataTable1.Columns.Count]; for(int row = 0; row < dtReportData.Rows.Count; row++) { for(int col = 0; col < dtReportData.Columns.Count; col++) { objectArray[row, col]...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface

If i have understood it correctly you want to get all selected parents and all selected children. You could use a recursive method: Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes) Get Return rootList.Where(Function(t) t.SelectedInTreeSelector). SelectMany(Function(root) GetSelectedChildren(root)). ToList() End Get End Property Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean =...

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

c#,linq

You need all the keywords to be present, so test keywords.All. Within that test for all, you need there to be a matching relevant keyword-reference, so test keywordReferences.Any: from f in forms where keywords.All( kw => keywordReferences.Any( kr => kr.KeywordId == kw.Id && kr.FormId == f.Id)) select f; ...

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

c#,.net,linq,lambda,clr

The DeclaredConstructors property will return even the static constructor of List<>. You clearly can't invoke it. Use: ConstructorInfo foundConstructor = objectType.GetTypeInfo().GetConstructor(Type.EmptyTypes); ...

Linq in C++ CLI

xml,linq,visual-c++,xpath,c++-cli

I was able to rewrite your code in such a way: using namespace System; using namespace System::Collections::Generic; using namespace System::Xml::Linq; using namespace System::Xml::XPath; ref class cROI { public: property int iX ; property int iY ; property int iWidth ; property int iHeight; cROI (int piX, int piY,int piWidth,int piHeight...

Grabbing most recent transaction/record

c#,linq

One way would be filtering by startDate, grouping by ID, ordering by date, and grabbing the first element of the group: var res = tx .Where(tx => tx.TransactionDate <= startDate) .GroupBy(tx => tx.Id) .Select(g => g.OrderBy(tx => tx.Date).First()); ...

How to convert to LINQ Queries

c#,linq,foreach

This should get you started: foreach (var pair in dict.Where(pair => input.DealInputs.ContainsKey(pair.Key))) { input.DealInputs[pair.Key] = pair.Value; } ...

VB LINQ - Take one random row from each group

vb.net,linq,random

One quick way to shuffle items is to sort by a "random" value - Guid.NewGuid() usually works well enough. Then just pull the first row from each group: Dim query = _ From rows As DataRow In surveyAnswerKeys.Rows _ Order By Guid.NewGuid() _ Group By questionSortKey = rows(answerGroup) _ Into...

Linq where clause with if condition

c#,linq

Something like this: .Where(m => !m.IsDeleted && (m.Project == null || !m.Project.IsDeleted)) You need to check if Project is null before checking if Project.IsDeleted. If you don't want the ones where project isn't null, then you just need: .Where(m => !m.IsDeleted && m.Project != null && !m.Project.IsDeleted) Remember: Shortcut evaluation...

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

c#,linq,entity-framework,sqlite

The biggest optimization would be changing the Contains to a StartsWith. Which would be equivalent to changing from name like '%search%' to name like 'search%'. Otherwise SQLite can't fully use the indexes you placed on the columns and you are basically searching the whole table. // First Name if (!string.IsNullOrEmpty(firstName))...

Asp.Net Identity find users not in role

asp.net,linq,entity-framework,asp.net-identity

In c# you can get all users that are not in a certain role like this: var role = context.Roles.SingleOrDefault(m => m.Name == "role"); var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id)); ...

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

sql,sql-server,linq,tsql

Using a subquery with a group by and having statement you can come up with something similar to this: SELECT * FROM Students WHERE StudentID NOT IN ( SELECT s.StudentID FROM Students s JOIN CourseEnrollment ce ON s.StudentID = ce.StudentID JOIN Courses c ON ce.CourseID = c.CourseID WHERE ce.EnrollmentStatus =...

get string array from another delimited string array

c#,arrays,string,linq

You can use Enumerable.Select along with String.Split string []arr = {"string:1", "string:1", "string:2"}; string [] result = arr.Select(e=>e.Split(':').Last()).ToArray(); To convert it to int array you can use Convert.ToInt32 int []result1 = arr.Select(e=>Convert.ToInt32(e.Split(':')[1].Last())).ToArray(); ...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...

Updating entity framework model using Linq

c#,sql,linq,entity-framework

You need to update your SQL server with the following columns: UserActivity_UserID, Orders_UserId. Or in the code remove this two columns(Map again your DB to the edmx file)....

“Left XOR” between two lists with LINQ

c#,linq,ienumerable

Using the Enumerable.Except: List<string> xorred = pIsinList.Except( diplayedBondsList.Select(x => x.isin)).ToList(); Note that this command will do implicitly a Distinct() on pIsinList (something that isn't explained in the MSDN, but that if you look at the source is quite clear), so if you had new[] { "A", "A" } in pIsinList,...

Linq implementation of for and if loop

c#,linq,loops

This is effectively the same as the answer from Stephen Kennedy, but I sometimes like this syntax. Usually for more complicated things, but still: foreach (var item in from l in list1 where l == eCode select l) { // Do something with each item } ...

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

c#,linq,linq-to-entities

You need to use Where with Contains: var selectedItems = db.Items.Where(x => locationIds.Contains(x.LocationId)); ...

C# lambda expressions without variable / parameter declaration?

c#,.net,linq,lambda

Methods don't accept lambdas as parameters. They accept delegates as parameters. A lambda is just one way of creating a delegate. Another way is supplying a method group, as is done in your second example, which can be converted to a delegate. A similar way is to use the anonymous...

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

c#,.net,string,linq

You can use Regular Expressions to filter the result: List<string> sList = new List<string>(){"AB012345", "AB12345", "AB123456", "AB1234567", "AB98765", "AB987654"}; var qry = sList.Where(s=>Regex.Match(s, @"^AB\d{6}$").Success); ...

How To optimise following linq to object query

c#,asp.net,linq,linq-to-objects

Well, couldn't you use a groupby ? var item3 = items.GroupBy (m => m.SKU) .Select(g => new { SKU = g.Key, colors = string.Join("," , g.Select(m => m.color_class) .Distinct()),//you could do a .OrderBy(m => m) after the distinct sizes = string.Join(",", g.Select(m => m.size) .Distinct())//you could do a .OrderBy(m =>...

Finding an item in a list in c#

c#,linq

You have your condition wrong, you are looking for questionanswers where the question does not match, you should be looking where they do match and checking that the result is null. (switch the != with ==) It should be if (questionnaire.QuestionAnswers.Find(a => a.Question == fataQuestionsAnswers.Question) == null) However I would...

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

c#,.net,linq,lambda,expression-trees

Don't use Expression.Call(innerLambda.GetMethodInfo(), ...), that's just asking for trouble. Invoke the delegate instead - you have no business messing around with the delegate's "method" - not only do you lose the target (quite important in instance methods), but you're also violating privacy (anonymous methods are internal or private, for example)....

Linq to XML select descendent of descendant each with specific attribute

c#,xml,linq

There are multiple options here, but I'd suggest the simplest thing is just to check each Grandchild: var grandchildren = doc .Descendants("Grandchild") .Where(x => (string) x.Parent.Parent.Attribute("name") == "Ken" && (string) x.Parent.Attribute("name") == "Lorna"); Or you could find all the relevant Child elements and then retrieves their children: var grandchildren =...

orderby () containing numbers and letters

c#,wpf,linq,linq-to-sql,sql-order-by

Given your example data where the first number is always a single digit: allScenes.OrderBy(x => x.SceneNumber).ToList() If you can possibly have multi-digit numbers, please provide them and where you want them in the sort order. This is one way to sort multiple digit numbers: var allScenes = new[]{ new {SceneNumber="4B"},...

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

c#,wpf,linq,datagrid

Here is the solution that works: private void tabControlOrganizer_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (tabControlOrganizer.SelectedItem != null) { if (e.Source is TabControl) { if (tabItemTrades.IsSelected) { dataGridTrades.ItemsSource = Queries.GetTradeList(dataContext); } SelectionChanged was the problem: In C# WPF, why is my TabControl's SelectionChanged event firing too often? In free time I...

Select XML Elements after last matching Element

c#,xml,linq

Simply select the last meal element: var lastMeal = noIdea.Elements("Meal").Last(); As an aside, you can simply cast an element to DateTime rather than converting the string value - e.g. (DateTime)el.Element("MealTime"). This uses DateTime.Parse internally with the correct styles as allowed in the XML specification....

Linq Conditional DefaultIfEmpty query filter

c#,linq,asp.net-mvc-5,linq-query-syntax

I solved it by adding the filter after the initial query, checking if the e.PractitionerProfiles were null. 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 =...

Sort Array by contains specific char count

c#,linq

Use: var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToList(); To count the number of words...

Update list of items in c#

c#,linq,list,updates

I would do something like this: (for ordinairy lists) // the current list var currentList = new List<Employee>(); currentList.Add(new Employee { Id = 154, Name = "George", Salary = 10000 }); currentList.Add(new Employee { Id = 233, Name = "Alice", Salary = 10000 }); // new list var newList =...

How to add empty value from gridview cell to list?

c#,linq,list,datagridview,datagridviewtextboxcell

Your problem is that your cell values can be string, DBNull.Value or null. null.ToString() throws the object reference not set to instance of an object exception. To avoid that you can first set your object as string to get rid of the DBNull.Value and then use the null-coalescing operator to...

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

c#,linq

So you want to remove all ProductUpdate instances from the sequence which have a match in the string-list according to the date? Since an IEnumerable<T> does not support Remove you have to re-create it: productUpates = productUpates .Where(pu => !datesList // your List<string> .Any(str => pu.DueDateTime == DateTime.Parse(str, CultureInfo.InvariantCulture))); If...

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4

Ensure term matches the case of the data. As all the data is loaded (.ToList() in the DAL), the .Where clause uses .Net comparison rather than SQL comparison: var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term, StringComparison.OrdinalIgnoreCase)... If, in the future, you want to change this to Contains, you can add an...

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

c#,linq,lambda,expression

Because where you see a single c parameter, in truth there are two different c parameters (let's call them c1 and c2). So when you merge the two expressions you have: c1 => c1.Something && c2.SomethingElse; And the CLR gets angry because it can't find the c2. Worse, as you...

LINQ: How to add multiple fields for grouping

c#,linq

If I understand you well, you need this: from line in csvLinesData group line by new { prop1 = line[12], Time = DateTime.Parse(line[0]).TimeOfDay } into newGroup orderby newGroup.Key.prop1, newGroup.Key.Time select newGroup; Since line[0] is a string (apparently), you have to parse it to a DateTime value. I show the most...

Order LINQ query elements by a collection of numbers

.net,vb.net,linq,compare,compareto

Change: OrderBy(Function(x) x.index.CompareTo(lineNumbers(x.index))) To: OrderBy(Function(x) lineNumbers.ToList().IndexOf(x.index)) Alternatively, if you changed the type of the lineNumbers parameter from IEnumerable(Of Integer) to List(Of Integer), then you wouldn't need to call the ToList method. Although, I have to say, while I love LINQ because it makes the code so much more readable, this...

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

c#,linq,sorting,dictionary

You can use List.Sort, LINQ doesn't work in this case because you can't modify the dictionary(f.e. Add or using the Value property) during enumeration: foreach(var kv in yourSortedDictionary) { kv.Value.Sort((p1, p2) => { int diff = p1.LastName.CompareTo(p2.LastName); if(diff != 0) return diff; return p1.FirstName.CompareTo(p2.FirstName); }); } This works even if...

ForEachAsyc with Result

c#,linq,task-parallel-library,task

Your LINQ query can only ever have the same number of results as the number of partitions - you're just projecting each partition into a single result. If you don't care about the order, you just need to assemble the results of each partition into a list, then flatten them...

Linq join and order by

c#,sql,linq

Try this: var file = (from f in context.Files join fa in context.FileActions on f.FileId equals fa.FileId where fa.ActionTaker == "Jeff" && f.FileStatus == 4 orderby fa.ActionDate descending select f).FirstOrDefault(); ...

Join 2 tables with multiple references in LINQ

c#,linq,linq-to-sql

Somewhere in the lines of: var query1 = (from t1 in table1s join t2 in table2s on t1.Id equals t2.Id1 where !string.IsNullOrEmpty(t1.Name) select new {t1.Name, t2.Id1, t2.Id2, t2.MatchLevel}); var query2 = (from t1 in table1s join t2 in table2s on t1.Id equals t2.Id2 where !string.IsNullOrEmpty(t1.Name) select new {t1.Name, t2.Id1, t2.Id2,...

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

c#,sql-server,linq,tsql

I think there is opportunity to rewrite your query, but for information purposes I rewrote your sql into linq verbatim. If you explain what you are trying to achieve we can provide alternative sql / linq var eqnums = new[] { "M0435", "Z0843" }; var testdate = "2008-06-01"; var query...

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

c#,linq

Solution 1: Simplest solution would be DefaultView.ToTable. dt.DefaultView.ToTable(true, "PONumber", "Customer", "Address"); Solution 2 : Another alternative would be using Linq statement to filter distinct rows and then looping them as required. var result = dt.AsEnumerable() .Select(row => new { PONumber = row.Field<string>("PONumber"), Customer = row.Field<string>("Customer"), Address = row.Field<string>("Address") }).Distinct(); Solution...

joining two collections in C# or JavaScript

javascript,c#,linq,collections

There are couple of ways on how you can achieve that, i am guessing you want to use a json file as a source file, so why not convert everything to objects and deal with them that way, which will provide more flexibility to manipulate them and perform more complication...

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

vb.net,linq

You can use Enumerable.All: dim linqMeddata = From m In medicineDataList Where keys.All(Function(k) m.MedicineData.Contains(k)) Order By m.MedicineName Ascending Select m ...

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

c#,linq

you're comparing string and char type replace where r1[4] == "I" / where r1[4] == "O" with where r1[4] == 'I' / where r1[4] == 'O'...

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

c#,oracle,linq,entity-framework

There is a very important difference between Enumerable.Where and Queryable.Where: Enumerable.Where takes a Func<T, bool>. Queryable.Where takes an Expression. Your filter variable is not an Expression, it is a Func<T, bool>, therefore, the compiler uses Enumerable.Where. What happens then is that all rows of your FOO table are transferred to...

ExecuteQuery returns empty collection when there is only a single result

c#,sql-server,linq

I don't know the exact issue you have, but it will of course return nothing if there are no table in the database. If you want to select all schemas better use: SELECT schema_id, name FROM sys.schemas ...

Linq query in C#

c#,linq

Without converting to Lambda expressions, you can do: XElement test = XElement.Load(new StringReader(xml)); var testThing = from thing in test.Descendants("vehicle") where thing.Descendants("vehicleType").FirstOrDefault().Value.ToString() == "Car" select thing; ...

Search functionality across many columns

c#,asp.net-mvc,linq

I guess the main question is, how should the value match against a numeric column? For example, if the column has "123" and "2" should match it, then you're essentially treating the column as a string rather than a number. In that case, just treat it like a string: ||...

Group by day, time and id in one LINQ

c#,linq

If you just want to group for displaying purposes, you don't need the classes GroupedByDay, GroupedByTime and GroupedById Considering examples is an IEnumerable<Example> var groupedExamples = from example in examples group example by new { example.SomeDate.Date, //Day example.SomeDate.Hour, // Hour example.Id // Id } into g select g; Then you'll...

Passing conditional parameters to Database.SqlQuery

c#,sql,linq,entity-framework

You can edit your query to this SELECT * FROM Product p WHERE p.ProductId = @ProductId AND (@CustomerId IS NULL OR p.CustomerId = @CustomerId) Then you pass DBNull.Value to @CustomerId if it is not used...

CSV File header part is coming parsing by LINQ

c#,linq,csv

You seem to be doing the Skip(1) in the wrong place: var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // IEnumerable<string[]> As it stands you're skipping the first column for each row, not the first row....

Remove the Parent Node based on Child condition

c#,xml,linq,linq-to-xml

If I understand you correctly: string first = "John"; string last = "D"; XDocument xd = XDocument.Parse(xml); xd.Root.Element("product").Elements("auto").ToList() .ForEach(x=> { var name = x.Descendants("name").First(); if (name.Element("first").Value != first && name.Element("last").Value != last) x.Remove(); }); Console.WriteLine(xd); Print: <result> <product> <auto> <report> <auto> <admin></admin> <report> <search> <subjects> <subject> <name>...

Using LINQ to reference XML local Xelements

c#,xml,linq

You always have the option to create extension methods to find elements by local name. Whether you like it or not, you have to "use an if within the foreach," that's an ovherhead you'll have to accept. This implementation is in terms of LINQ but you could always write it...

Check if a List contains specific types (multiple)

c#,linq

You can do the following (if there's typo's, I blame the sidetracking thought of crispy bacon as we near lunch time): var types = new List<Type> { typeof(Smokey), typeof(Rasher), typeof(Danish) }; As mentioned in comments, for every item in your bacon list, you want the first matching corresponding type from...

Casting a list of objects to another one

c#,linq,casting,lambda,dao

The return type of Read() is probably something like IEnumerable<Entity> or List<Entity>. That's why you can't cast them to a single Category. If you need a one line solution for this, you could try var categories = categoryDao.Read().OfType<Category>(); or (thanks @Binkan Salaryman) var categories = categoryDao.Read().Cast<Category>(); (the former will return...

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

asp.net,.net,vb.net,linq,datatable

In the past, I've done this sort of like this: Dim item = From r as DataRow in dtCodes.Rows Where lstCodes.contains(r.Item("Codes")) Select r Does that work?...

C# Refactoring gigantic switch statement for ordering with LINQ

c#,asp.net-mvc,linq,dry

The OrderBy function works by letting you return the property it should sort on, it will be called foreach item in the list. Instead of hardcoding it, we can use reflection instead: public ActionResult Index(AgentReportViewModel vm) { var b = Agent.GetAgents(); vm.Agents = vm.SortAscending ? b.OrderBy(x => GetValueByColumn(x, vm.SortByColumn)) :...

Can't access any of Linq methods

linq,asp.net-web-api

The non-generic IQueryable interface doesn't have extension methods of Count and ToList(). Only the generic IQueryable<T> does. If you can modify the library to return a suitable IQueryable<T>, I suggest you do so. If you can't, you may need to call Cast<T>() or OfType<T>() to create an appropriate IQueryable<T> with...

Linq update with specific select of column being null

c#,linq

The problem you have is that your model is not identical to you database, if you could select the row directly (you said Linq2SQL and not Linq2Entities) then you could update it again, which you do. If you select an anonymous type then you lose the context connection and cannot...

Get a single text value using linq

c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3

Change your Select to be a Where. Where uses a predicate to filter the data and return the same structure...just a subset. Select on the other hand changes the data structure to be whatever is evaluated in the provided function. In your case you are changing the structure to be...

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

asp.net,linq

Try this lblMonth.Text=months.Month; lblCount.Text=months.Count; Also you have to call FirstOrDefault() or ToList() in order to select data. Currently you code will not select data. var months = dates.GroupBy(x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count() }).FirstOrDefault(); OR var months = dates.GroupBy(x => x.Value.Month).Select(g => new {...

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

c#,linq,string-comparison

This works for me: public static bool IsContainedWithin(this string @this, string container) { var lookup = container.ToLookup(c => c); return @this.ToLookup(c => c).All(c => lookup[c.Key].Count() >= c.Count()); } I tested it like this: var tests = new [] { "met".IsContainedWithin("meet"), "meet".IsContainedWithin("met"), "git".IsContainedWithin("light"), "pall".IsContainedWithin("lamp"), }; I got these results: True False...

Listing directories by content size using C# [closed]

c#,.net,windows,linq

A small example here: class DirectorySize { public string DirectoryName; public long DirectorySizes; } public class Program { static void Main(string[] args) { string[] cDirectories = Directory.GetDirectories("C:\\"); List<DirectorySize> listSizes = new List<DirectorySize>(); for (int i = 0; i < cDirectories.Length; i++) { long size = GetDirectorySize(cDirectories[i]); if(size != -1) {...

LINQ Group By and not contains usage issue

c#,linq

It's not SQL but C#, so a string has quotes not apostrophes and it's && not and, change it to: where !line[12].Contains("VM") && !line[12].Contains("Voice Mail") ...

Using Linq with VB.NET

vb.net,linq

You're still using c# syntax for your lambda expression. See http://msdn.microsoft.com/en-us/library/bb531253.aspx for details of Lambda expressions in vb. In your case its as simple as val1 = val1.OrderBy(Function (c) c ).ToArray ...

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

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Load XML to list using LINQ [duplicate]

c#,xml,linq

Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....

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

c#,linq,distinct

You need to actually pass the IEqualityComparer that you've created to Disctinct when you call it. It has two overloads, one accepting no parameters and one accepting an IEqualityComparer. If you don't provide a comparer the default is used, and the default comparer doesn't compare the objects as you want...

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

c#,.net,linq,ienumerable,iqueryable

myEnumerable.AsQueryable() returns a custom object: new EnumerableQuery<TElement>(myEnumerable); (source code) This EnumerableQuery class implements IEnumerable<T> and IQueryable<T> When using the EnumerableQuery result of .AsQueryable() as an IEnumerable, the implementation of the interface method IEnumerable<T>.GetIterator() simply returns the original source iterator, so no change and minimal overhead. When using the result of...

nested IN subquery in linq to sql

sql,linq,linq-to-sql

Everything is fine in your code there is only one mistake i guess. change select iq.AffiliateId to => iq.LenderId var innerquery = from iq in db.AffiliateLenderRelations where iq.AffiliateId == loggedInUser.UserId select iq.AffiliateId; List<SelectListItem> lenders = db.Users .Where(o => o.AccountTypeId == 1 && o.Deleted == false && innerquery.Contains(o.UserId)) .Select(o => new...

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

c#,asp.net,linq,sql-server-2008

How about this? var dates = Enumerable.Range(1, 5).Select(i=>new DateTime(2015,i%3+1,1)); var grouped = dates.GroupBy(d => d.Month).Select(g => string.Format("{0}={1}", g.Key, g.Count())); // Now grouped will have your desired data (list of occurrences) I have used dummy dates here. You need to Select the date column from the database instead....

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

c#,linq

You make an order by on your entity. You should do it on one of the property of your entity orderby s.SupplierName or multiple properties, of course : orderby s.SupplierName, s.SupplierLastName, s.SupplierBirthDate descending ...

Please help me convert this sql to LINQ

linq

something in the line of...i didn't test this but you may have to do Datetime.Parse etc if needed... (from r1 in dt.Rows.OfType<DataRow>() from r2 in dt.Rows.OfType<DataRow>() where r1["timestart"] < r2["timeend"] && r2["timestart"] < r1["timeend"] && r1["pfid"] != r2["pfid"] select new {R1=r1, R2=r2}) ...

LINQ to Entities Retrieving related Entities or T-SQL

c#,sql-server,linq

you can try selecting from Vendors and using Any() for ShowId. Vendor[] vendorsInShow = (from v in db_.Vendor .Include("Products.Pics") .Where(m => m.Booths.Any(a => a.ShowID == showId) && m.Products.Count > 0) select v).AsNoTracking().ToArray(); ...

LINQ pad is showing SUM at end of result

linq,linqpad

LINQad will return results in its Results tab, any enumeration will have at the top of its blue box something like: IEnumerable<EventLogEntry> (114 items) Depending on the exact type. That count at the end is a LINQPad feature when it serializes the data for display, and it is the count...

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

c#,linq

Why not replace your original function by: Dictionary<string, Dictionary<string, object>> DataTableToDictionary(DataTable dt, string prefix, string id) { var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != id); return dt.Rows.Cast<DataRow>() .ToDictionary(r => prefix + r[id].ToString(), r => cols.Where(c => !Convert.IsDBNull(r[c.ColumnName])).ToDictionary(c => c.ColumnName, c => r[c.ColumnName])); } ...

How to write Nested LINQ for specific scenario

c#,linq

This is a good example of something to do in Linq. You will find that you can do this easily and even more powerful queries if you understand two things: Don't try to overly literally translate from SQL into Linq. Lambdas. The first is easy to understand but hard to...

Issue displaying LINQ query results in a grid in C#

c#,linq

I solved my own problem. Here is what I did: Created a class for the attributes needed: public class dataRow { public string CenterName { get; set; } public string CenterCode { get; set; } public string NextImport { get; set; } public string NextExport { get; set; } public...

Add children to XElement via LINQ

c#,xml,linq

Like this: var element = new XElement( "Ou", new XElement("Group", "AAA"), new XElement("Group", "BBB"), new XElement("Group", "CCC"), new XElement("Group", "DDD")); Or from your data structure: var element = new XElement("Ou", from g in _groups select new XElement("Group", g.Name)); ...