w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » LINQ » Page 1
Linq query will change often- how can I change it without recompiling app?
Linq2SQL is innately code-based. If your schema is going to change, then the code will need to change. The only way I can see around this, and still get some of the benefits of linq, is to write everything as Stored Procedures, which you can than add as method to the linq DataContext. Then, as long as the Name, input parameters and output columns remain the same, you can change what the SP is d

Categories : Linq

WCF service And Linq
I have solved the problem. The query that i use for extracting data from the database i somthing called lazyloading. And WCF have trouble working with this kind of query if the data that need's to be extracted is to complex. It is somthing about how WCF service serialize the service. So what i did to make it work was to go in the Linq datacontex and set the. Serialization Mode to Unidirectional. T

Categories : Linq

linq excluding one result set from another
Here is the final working solution, took a lot of playing with to get it working var AllForms = db.ClinicForms.Where(d => d.ClinicId == clinicId); var SignedForms = AllForms.Where(d => d.SignedForm.FormSigned == d.Id && d.SignedForm.PatientId == patientId); var res = AllForms.Except(SignedForms);

Categories : Linq

N-Ary/Multiple-List Cartesian Product
I'd put them in a list of string arrays. Then I'd use ForEach: IEnumerable<string> result = list.First(); list.RemoveAt(0); list.ForEach(delegate(IEnumerable<string> value) { result = (from r in result from v in value select r + " " + v).ToList(); }); You can also see this link : Cartesian Product for Group members

Categories : Linq

Linq Lambda multiple tables ( 4 tables ) LEFT JOIN
I cannot test now if will work, but sometimes you can write the GroupJoin like (if you expect 0 or N registers from T1): .GroupJoin(MyContext.T1, q1 => q1.TMainId, q2 => q2.TMainId, (x, y) => new { A = x, T1_A = y.DefaultIfEmpty() }) or (if you expect 0 or 1 registers from T1) .GroupJoin(MyContext.T1, q1 => q1.TMainId, q2 => q2.TMainId, (x, y) =>

Categories : Linq

Parsing string values to correct type in dynamic linq queries
Have you tried checking the searchField for null before passing it to .ToString() So do something like: foreach (var searchField in searchFields) { products = products.Where(searchField + " != null && " + searchField + ".ToString() == @0", searchText); }

Categories : Linq

Sequence contains no elements when using count on LINQ Query
This error for me was caused by visual studio using an old build instead of my current build. I don't know why it does this, but I've had it happen in visual studio 2012 and 2013. Just deleting the bin folder fixed it. In your case, I think the problem is that you're using the Count() method instead of the Count property.

Categories : Linq

order list by using sum of its fields
You need to use order by after selecting SUM() as :: SharedStories = (from p in PublishedLivestories.ToList() select new{ totlaSharedCountOfStory = p.Sum(s => s.SharedOnFacebookCount + s.SharedOnGoogleCount + s.SharedOnIns

Categories : Linq

Linq Select Into using T-SQL Function
Well, SELECT INTO is used to insert data, which Linq is not designed for, but the query part would be: var visible = ( from f in allTasks // to lookup foreach and return clean where func_GetTaskVisibility(taskId,state) = 1 select f ).ToList();

Categories : Linq

Converting C# Expression Parsing to F#
I'm not sure if an exact translation of this is possible using quotations because quotations have a different shape than C# expressions. However, here's something along the same lines: open Microsoft.FSharp.Quotations.Patterns let GetMemberName = function | Call (_,methodInfo,_) -> methodInfo.Name | PropertyGet (_,propertyInfo,_) -> propertyInfo.Name | _ -> failwith "Not a m

Categories : Linq

How to get total count of children of a class containing Dictionary of same type?
A typical solution to this problem is to create a recursive method, like this: public class Node { public readonly IDictionary<string, Node> _nodes = new Dictionary<string, Node>(); public int GetTotalChildrenCount() { return _nodes.Values.Sum(n => n.GetTotalChildrenCount() + 1); } } + 1 part is used to count a node itself, apart from the number o

Categories : Linq

Using Linq to XML using C#, how do I find attribute values?
You're currently converting the value to a string but then comparing it with an int. Don't do that - it's not going to work :) It's probably simplest to convert it to an int instead: var Activites = (from e in Doc.Descendants("Activity") where (int)Doc.Element("Claim").Element("ID") == 13 ...) Next, look at your XML - the Claim element isn't inside an Activ

Categories : Linq

Linq to SharePoint broken after converting columns to content types
So say you have a list called Documents. It has two columns called 'One' and 'Two'. You make your Linq to SP queries just fine: DataContext dc = new DataContext("http://sharepoint"); var varResults = (from item in dc.Documents where item.Two == "blah" orderby item.One descending select item); Then you decide you want to use content types w

Categories : Linq

List with two columns - using partial search
It's not clear what exactly you're trying to do. You might want: list = list.Where(emp => emp.Name == name).ToList(); or perhaps list = list.Where(emp => emp.Name.Contains(name)).ToList(); It's not at all clear why you'd be trying to use Any though. EDIT: Given the comment, I suspect you really want: list = list.Where(emp => emp.Name.StartsWith(name)).ToList(); (You might need t

Categories : Linq

Is there a way to ONLY add tables to an edmx file?
Sure, If you right click on your EDMX model diagram. You can select update model from database. A dialogue box will pup up. The dialogue box has tabs up at the top one of them is add. From there expand the table menu and select the tables you want to add. Update 11/08/2014 In this example Deleted table no longer exists in the Database. Open up your EDMX file. Right click in the white space aroun

Categories : Linq

Create Pie Chart using MVC 5 and Entity Framework
MVC has chart helper that you can get using System.Web.Helpers.dll if you're not doing some fancy highly interactive chart. For other HTML5 and JS/Jquery based Free/Open-Source library checkout Google chart library Jqplot Update: you need to provide array instead of just throwing dataView as the datasource, In your scenario, xValue = array of AnalystID yValue = array of RequestID

Categories : Linq

Linq: Produce one result from two linq sources
You just use Concat as you have. But instead of linq.Concat(linq2), you just put the queries there: var joined = list1.Where (w => w.Contains("o")) .Concat(list2.Where (w => w.Contains("l"))); Concat doesnt have a query syntax equivalent. (http://msdn.microsoft.com/en-us/library/bb386979(v=vs.110).aspx) So you'd do something like this: var joined = (from item in list1

Categories : Linq

Linq with GroupBy, Order, and FirstOrDefault using Navigation property
q = q.Where(a => a.Date <= d).GroupBy(a => a.CompanyId).OrderByDescending(t => t.Date).FirstOrDefault(); This should work for you without knowing more about the data structure or what your trying to achieve as the end result. A good tool for helping to write linq is LINQPad

Categories : Linq

IQueryable with String.Format and PatIndex
You have two method calls: String.Format SqlFunctions.PatIndex Problem is, that the first one cannot be transformed into proper SQL query and the second one can only be executed within LINQ to Entities query context. Former makes your first attempt fail, latter breaks second try. However, I don't see A nor B be part of the data you query. You should be able to call string.Format outside of yo

Categories : Linq

Linq Pivot Query on Column with Unknown Values
Do you know the most granular values that the user can choose ? If for example it's months, then you can simply write a query for months (see Is it possible to Pivot data using LINQ?). If the user then chooses years, it should be simple to aggregate those values to years. If they want quarters, then you can aggregate to quarters and so on. It's maybe not the best/most generic solution, but it shou

Categories : Linq

Database.SqlQuery with ViewModel and Include results in blank FK values
I have tried the following statement, which works fine No, it doesn't, because the Include doesn't do anything. It compiles and runs, but the returned type, DbSqlQuery<Order> doesn't have an implementation of Include, so the method is ignored. You tried to fix that with the AsQueryable call, but that only "re-activates" the extension method Include, but it doesn't magically inject an In

Categories : Linq

Using LINQ with dynamic variables in C#
My understanding of the problem is that dAnimal.listFood type is unknown at compilation time, because dAnimal is dynamic. So compiler can't guarantee, that listFood is IEnumerable and it's item has foodName property. However, if you will use delegate, every listFood item will implicitly be casted to type of delegate input parameter (you will still have a problem with collection type). Any way, t

Categories : Linq

"Range variable name can be inferred only from a simple or qualified name with no arguments" error in linq query
I just ran into this and thought I'd see if there were any open questions on SO that need this answer. The line with the problem: If (cc.ContentTypeID = 2, from cf in CourseFiles Where cf.CourseFileID = cc.ContentID select cf, Whats is happening is that the last comma is ambiguous. It's possible to select multiple items, like select x, y, z, ..., and so that last comma is interpreted that way,

Categories : Linq

C# Lambda with Console.Read
int nTestCase = Convert.ToInt32(Console.ReadLine()); string[] inputStrings = Enumerable.Range(0, nTestCase) .Select(x => Console.ReadLine()) .ToArray(); or even string[] inputStrings = Enumerable.Range(0, Convert.ToInt32(Console.ReadLine())) .Select(x => Console.ReadLine())

Categories : Linq

NHibernate querying with WHERE conditions in pairs
This would be difficult with LINQ I think, but if you use QueryOver it's easy to build a WHERE clause dynamically using Restrictions.Disjunction: var disjunction = Restrictions.Disjunction(); foreach (Event evt in events) { disjunction.Add(Restrictions.Where<Table>( t => t.project_id == evt.project_id && t.name == evt.name); } var rows = session.QueryOver<Table&g

Categories : Linq

How do I remove entries in a tuple with duplicated properties?
var distincts = fileList.GroupBy(t => t.Item1 + "," + t.Item3) .Where(g => g.Count() == 1) .Select(g => g.Single()); foreach (var item in distincts) { Console.WriteLine(item); } This groups your tuples by Name/Phone, then keeps only groups that contain single tuples, and then selects that single tuple for the output list of distinct tup

Categories : Linq

How to retrieve both value & currency type from currency type attribute
The currency is stored inside the transactioncurrencyid field. It's a lookup so by code is an EntityReference. var currencyRef = (EntityReference)opportunity.GetAttributeValue("transactioncurrencyid"); after you can retrieve the currency details using the Id property (so will be like currencyRef.Id)

Categories : Linq

Retrieving information from derived child object collections using LINQ
OK, after a good night sleep, being all bright-eyed and bushy-tailed, I figured out my own problem. First the updated code was all wrong. Because each derived WorkflowStep has access to the Workflow and each MultiWorkflowStep contains a list of SingleWorkflowSteps - when I get the list of all SingleWorkflowSteps (which would include all from MultiWorkflowStep(s)), I simply needed to get a list of

Categories : Linq

Using distinct on a column while getting multiple column data
You can group them: IEnumerable<CModel> model = db.dbModels.AsEnumerable() .GroupBy(x => new { x.Property, x.Type }) .Select(x => new CModel { CName = "XXX", PName = x.Property, PType = x.Type }).ToList()

Categories : Linq

Replace null returned date with a DateTime.now with C# and Linq
Try this : var model = from c in db.VW_myTable select new { COdUser = c.CodUser, Entrada = c.StartHour, Salida = c.EndHour, fecha = c.DATE ?? DateTime.Now }; Check this post for a detailed explanation about ?? operator.

Categories : Linq

Combining Linq Expressions for Dto Selector
I thought about it a little, and I didn't come up with any "awesome" solution. Essentially you have two general choices here, Use placeholder and rewrite expression tree entirely. Something like this, public static Expression<Func<ClassA, DtoA>> DtoExpression{ get{ Expression<Func<ClassA, DtoA>> dtoExpression = classA => new DtoA(){ BDto =

Categories : Linq

Why linq isn't grouping/counting as expected
Your grouping isn't really grouping anything. You need to come up with a key to group by, not the entity itself. Apparently you should be grouping by Product. var query = (from click in this._dc.Clicks group click by click.Product into g let count = g.Count() orderby count descending select new { Product = g.Key, Total = count }).Take(3);

Categories : Linq

'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' 'object' does not contain a definition for 'intEmployeeId'
ViewBag is a dynamic object and your setting the property to a collection of anonymous objects. In you foreach loop @foreach (var item in ViewBag.SeparationList) item is typeof object and object does not have a property intEmployeeId (or any of the other properties your define in the anonymous object). One way to handle this is to create a view model with the properties you want to display p

Categories : Linq

How to use LINQ Group By with Count
pseudocode var results = ( from r in ProductsReviews join p in Products on r.ProductId equals p.Id join b in Brands on p.BrandId equals b.Id group c by new { b.Id, b.ShortName } into grp select new { Id = grp.key.Id, ShortName = grp.key.ShortName, TotalReviews =

Categories : Linq

LINQ - Is Where(Predicate).FirstOrDefault() the same as FirstOrDefault(Predicate)
Because method chains in Linq are lazily evaluated, there shouldn't be any material difference between the two. Where.FirstOrDefault will stop executing when it obtains a value, just as FirstOrDefault(Predicate) will. To put it another way, FirstOrDefault (or any other Linq operator downstream, for that matter) accepts items one at a time from Where for evaluation, not the entire list at once (T

Categories : Linq

NSubstitute not matching Linq Expression
The default equality comparer for an Expression is being used (referential equality): eg, the expression (t => t.CreatedDate == createdDate && t.Status == Status``) in: this.myRepository.Received().Query<Thing>(t => t.CreatedDate == createdDate && t.Status == Status); Is a different instance to the expression in: return this.myRepository.Query<Thing>(t => t.C

Categories : Linq

Error - Corresponding column type must be compatible - DateTime field - Entity Framework, Informix, Load multiple childs
In your class definition for Cmrcl_Invc_Line_Item, you can try manually specifying the database data type for the last_change_ts property using the Column attribute. For example: [Column(TypeName="datetime year to second")] public DateTime last_change_ts {get; set;} That should change the type used in the generated query.

Categories : Linq

Fetch single value with linq projection query without using FirstOrDefualt
It looks like maybe your outer select is capable of returning multiple results (e.g. if there are more than one UserDetailsModel with the same Id). If it returns multiple results then your call to .SingleOrDefault() will throw an exception as it expects only a single result or no results. See LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria for more details.

Categories : Linq

How to query against multiple child elements using contains similarly to SQL's IN statement
Try this way : List<User> usersData = rep.GetUsersProfilesAndCompanies() .Where(u => u.CompanyStructures.Any(o => targetCompanyIDs.Contains(o.ID))) .ToList();

Categories : Linq




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.