Search Results

Search found 968 results on 39 pages for 'lambda'.

Page 13/39 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Access the value of a member expression

    - by Schotime
    If i have a product. var p = new Product { Price = 30 }; and i have the following linq query. var q = repo.Products().Where(x=>x.Price == p.Price).ToList() In an IQueryable provider, I get a MemberExpression back for the p.Price which contains a Constant Expression, however I can't seem to get the value "30" back from it. Cheers.

    Read the article

  • Return an empty collection when Linq where returns nothing

    - by ahsteele
    I am using the below statement with the intent of getting all of the machine objects from the MachineList collection (type IEnumerable) that have a MachineStatus of i. The MachineList collection will not always contain machines with a status of i. At times when no machines have a MachineStatus of i I'd like to return an empty collection. My call to ActiveMachines (which is used first) works but InactiveMachines does not. public IEnumerable<Machine> ActiveMachines { get { return Customer.MachineList .Where(m => m.MachineStatus == "a"); } } public IEnumerable<Machine> InactiveMachines { get { return Customer.MachineList .Where(m => m.MachineStatus == "i"); } } Edit Upon further examination it appears that any enumeration of MachineList will cause subsequent enumerations of MachineList to throw an exeception: Object reference not set to an instance of an object. Therefore, it doesn't matter if a call is made to ActiveMachines or InactiveMachines as its an issue with the MachineList collection. This is especially troubling because I can break calls to MachineList simply by enumerating it in a Watch before it is called in code. At its lowest level MachineList implements NHibernate.IQuery being returned as an IEnumerable. What's causing MachineList to lose its contents after an initial enumeration?

    Read the article

  • LINQ: How to Use RemoveAll without using For loop with Array

    - by CrimsonX
    I currently have a log object I'd like to remove objects from, based on a LINQ query. I would like to remove all records in the log if the sum of the versions within a program are greater than 60. Currently I'm pretty confident that this'll work, but it seems kludgy: for (int index = 0; index < 4; index++) { Log.RemoveAll(log => (log.Program[index].Version[0].Value + log.Program[index].Version[1].Value + log.Program[index].Version[2].Value ) > 60); } The Program is an array of 4 values and version has an array of 3 values. Is there a more simple way to do this RemoveAll in LINQ without using the for loop? Thanks for any help in advance!

    Read the article

  • Detecting that a MemberExpression has a value

    - by cs
    How do I detect if a MemberExpression has a value that needs to be compiled/evaluated? I have two separate member expression outputs, the first which has a value, and the second which doesn't. What is the best way to differentiate between the two? exp **{value(Microsoft.Connect.Api.Client.Tests.SearchQueryUnitTests+<>c__DisplayClass6).handle}** [System.Linq.Expressions.MemberExpression]: **{value(Microsoft.Connect.Api.Client.Tests.SearchQueryUnitTests+<>c__DisplayClass6).handle}** NodeType: MemberAccess Type: {Name = "String" FullName = "System.String"} vs exp {x.CreatedBy} [System.Linq.Expressions.MemberExpression]: {x.CreatedBy} NodeType: MemberAccess Type: {Name = "String" FullName = "System.String"}

    Read the article

  • C#: Is it possible to use expressions or functions as keys in a dictionary?

    - by Svish
    Would it work to use Expression<Func<T>> or Func<T> as keys in a dictionary? For example to cache the result of heavy calculations. For example, changing my very basic cache from a different question of mine a bit: public static class Cache<T> { // Alternatively using Expression<Func<T>> instead private static Dictionary<Func<T>, T> cache; static Cache() { cache = new Dictionary<Func<T>, T>(); } public static T GetResult(Func<T> f) { if (cache.ContainsKey(f)) return cache[f]; return cache[f] = f(); } } Would this even work? Edit: After a quick test, it seems like it actually works. But I discovered that it could probably be more generic, since it would now be one cache per return type... not sure how to change it so that wouldn't happen though... hmm Edit 2: Noo, wait... it actually doesn't. Well, for regular methods it does. But not for lambdas. They get various random method names even if they look the same. Oh well c",)

    Read the article

  • Dynamic expression tree how to

    - by Savvas Sopiadis
    Hello everybody! Implemented a generic repository with several Methods. One of those is this: public IEnumerable<T> Find(Expression<Func<T, bool>> where) { return _objectSet.Where(where); } Given to be it is easy to call this like this: Expression<Func<Culture, bool>> whereClause = c => c.CultureId > 4 ; return cultureRepository.Find(whereClause).AsQueryable(); But now i see (realize) that this kind of quering is "limiting only to one criteria". What i would like to do is this: in the above example c is of type Culture. Culture has several properties like CultureId, Name, Displayname,... How would i express the following: CultureId 4 and Name.contains('de') and in another execution Name.contains('us') and Displayname.contains('ca') and .... Those queries should be created dynamically. I had a look in Expression trees (as i thought this to be a solution to my problem - btw i never used them before) but i cannot find anything which points to my requirement. How can this be costructed? Thanks in advance

    Read the article

  • What is the cleanest way to use anonymous functions?

    - by Fletcher Moore
    I've started to use Javascript a lot more, and as a result I am writing things complex enough that organization is becoming a concern. However, this question applies to any language that allows you to nest functions. Essentially, when should you use an anonymous function over a named global or inner function? At first I thought it was the coolest feature ever, but I think I am going overboard. Here's an example I wrote recently, ommiting all the variable delcarations and conditionals so that you can see the structure. function printStream() { return fold(function (elem, acc) { ... var comments = (function () { return fold(function (comment, out) { ... return out + ...; }, '', elem.comments); return acc + ... + comments; }, '', data.stream); } I realized though (I think) there's some kind of beauty in being so compact, it is probably isn't a good idea to do this in the same way you wouldn't want a ton of code in a double for loop.

    Read the article

  • Inline HTML Syntax for Helpers in ASP.NET MVC

    - by kouPhax
    I have a class that extends the HtmlHelper in MVC and allows me to use the builder pattern to construct special output e.g. <%= Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.Field(model => model.PropertyThree); }) %> Which outputs some application specific HTML, lets just say, <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>PropertyThree: true</li> </ul> What I would like to do, however, is add a new builder methid for defining some inline HTML without having to store is as a string. E.g. I'd like to do this. <% Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.ActionField(model => %> Generated: <%=DateTime.Now.ToShortDate()%> (<a href="#">Refresh</a>) <%); }).Render(); %> and generate this <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>Generated: 29/12/2008 <a href="#">Refresh</a></li> </ul> Essentially an ActionExpression that accepts a block of HTML. However to do this it seems I need to execute the expression but point the execution of the block to my own StringWriter and I am not sure how to do this. Can anyone advise?

    Read the article

  • Coolest C# LINQ/Lambdas trick you've ever pulled?

    - by chakrit
    Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder... What's the coolest (as in the most elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written? Bonus if it has went into production too!

    Read the article

  • How does the proc in the caches_action if clause get execute

    - by Sid
    I have a newbie kind of question which I cant get my head around. How does the Proc in the if condition of the caches_action get executed for the caches_action method. for example caches_action :show, :if=Proc.new{|x| something} what i dont get its how does this get called. I know i can execute a proc defined as proc= Proc.new by proc.call so i dont understand how this gets called. Second how do I pass conditions like if logged_in? I'd appreciate any help on this

    Read the article

  • Is there something like LINQ for Java?

    - by Kb
    Started to learn LINQ with C#. Especially LINQ to Objects and LINQ to XML. I really enjoy the power of LINQ. I learned that there is something called JLINQ a Jscript implementation. Also (as Catbert posted) Scala will have LINQ Do you know if LINQ or something similar will be a part of Java 7? Update: Interesting post from 2008 - http://stackoverflow.com/questions/346721/linq-for-java

    Read the article

  • Lamda expression will not compile

    - by John Soer
    I am very confused I have this lamba expression tvPatientPrecriptionsEntities.Sort((p1, p2) => p1.MedicationStartDate.Value.CompareTo(p2.MedicationStartDate.Value)); Visual studio will not compile it and complains about syntax. I converted the lamba expression to an anonymous delegate as so tvPatientPrecriptionsEntities.Sort( delegate(PatientPrecriptionsEntity p1, PatientPrecriptionsEntity p2) { return p1.MedicationStartDate.Value.CompareTo(p2.MedicationStartDate.Value); } ); and it works fine. The project is uses the .net 3.5 framework and I have a reference to system.linq.

    Read the article

  • How can I get the type I want?

    - by Danny Chen
    There are a lot of such classes in my project (very old and stable code, I can't do many changes to them, maybe slight changes are OK) public class MyEntity { public long ID { get; set; } public string Name { get; set; } public decimal Salary { get; set; } public static GetMyEntity ( long ID ) { MyEntity e = new MyEntity(); // load data from DB and bind to this instance return e; } } For some reasons, now I need to do this: Type t = Type.GetType("XXX"); // XXX is one of the above classes' name MethodInfo staticM= t.GetMethods(BindingFlags.Public | BindingFlags.Static).FirstOrDefault();// I'm sure I can get the correct one var o = staticM.Invoke(...); //returns a object, but I want the type above! If I pass "MyEntity" at beginning, I hope I can get o as MyEntity! Please NOTE that I know the "name of the class" only. MyEntity e = staticM.Invoke(...) as MyEntity; can't be used here.

    Read the article

  • OrderBy Linq.Expression as parameter = (Of Func(Of T,IComparable)) to perform LinqToEntity is not working

    - by NicoJuicy
    I'd like to get this working: Call: (Count & Page are used for pagination, so Count = 20 and Page = 1 for example, for the first 20 values). Sorting should be by name LeverancierService.GetLeveranciers(Function(el) el.Name, Count, Page) Equivalent in c#: LeverancierService.GetLeveranciers(el= el.Name, Count, Page) Method that gives an error (parameters shown above): Public Overridable Function GetAllPaged(orderby As Expression(Of Func(Of T, IComparable)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T) Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList() End Function Already tried changing it to this, but it gives the same error: Public Overridable Function GetAllPaged(Of TOrderBy)(orderby As Expression(Of Func(Of T, TOrderBy)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T) Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList() End Function Error: Unable to cast the type 'System.String' to type 'System.IComparable'. LINQ to Entities only supports casting Entity Data Model primitive types. Any idea how to do this? Extra info: I'm in a DDD-layered application, so the parameter should stay the same as the called method is an overridden interface (eg. if i change this, i have to do this for 200 times or so, because it's in VB.Net and not in C# (= 1 change) ) I know there is a way to change the expression to a string and then use DLinq (= Dynamic Linq), but that's not how it should be.

    Read the article

  • How can I pass in a params of Expression<Func<T, object>> to a method?

    - by Pure.Krome
    Hi folks, I have the following two methods :- public static IQueryable<T> IncludeAssociations<T>(this IQueryable<T> source, params string[] associations) { ... } public static IQueryable<T> IncludeAssociations<T>(this IQueryable<T> source, params Expression<Func<T, object>>[] expressions) { ... } Now, when I try and pass in a params of Expression<Func<T, object>>[], it always calls the first method (the string[]' and of course, that value isNULL`) Eg. Expression<Func<Order, object>> x1 = x => x.User; Expression<Func<Order, object>> x2 = x => x.User.Passport; var foo = _orderRepo .Find() .IncludeAssociations(new {x1, x2} ) .ToList(); Can anyone see what I've done wrong? Why is it thinking my params are a string? Can I force the type, of the 2x variables?

    Read the article

  • How to get XML into a Dictionary with an Expression?

    - by DaveDev
    I have the following XML: <PerformancePanel page="PerformancePanel.ascx" title=""> <FundGroup heading="Net Life Managed Funds"> <fund id="17" countryid="N0" index="24103723" /> <fund id="81" countryid="N0" index="24103723" /> <fund id="127" countryid="N0" index="24103722" /> <fund id="345" countryid="N0" index="24103723" /> <fund id="346" countryid="N0" index="24103723" /> </FundGroup> <FundGroup heading="Net Life Specialist Funds"> <fund id="110" countryid="N0" index="24103717" /> <fund id="150" countryid="N0" index="24103719" /> <fund id="119" countryid="N0" index="24103720" /> <fund id="115" countryid="N0" index="24103727" /> <fund id="141" countryid="N0" index="24103711" /> <fund id="137" countryid="N0" /> <fund id="146" countryid="N0" /> <fund id="133" countryid="N0" /> <fund id="90" countryid="N0" /> <fund id="104" countryid="N0" /> <fund id="96" countryid="N0" /> </FundGroup> </PerformancePanel> I can get the data into an anonymous object as follows: var offlineFactsheet = new { PerformancePanels = (from panel in doc.Elements("PerformancePanel") select new PerformancePanel { PerformanceFunds = (from fg in panel.Elements("FundGroup") select new { Heading = (fg.Attribute("heading") == null) ? "" : (string)fg.Attribute("heading"), Funds = (from fund in fg.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList() }).ToDictionary(xx => xx.Heading, xx => xx.Funds)}; I'm trying to change my code such that I can assign the dictionary directly to a property of the class I'm working in, as described in this question. I'd like to have a Dictionary() where each header text is the key to the list of funds under it. I'm having difficulty applying the example in the linked question because that only returns a string, and this needs to return the dictionary. This is the point that I got to before it occurred to me that I'm lost!!!: this.PerformancePanels = doc.Elements("PerformancePanel").Select(e => { var control = (PerformancePanel)LoadControl(this.OfflineFactsheetPath + (string)e.Attribute("page")); control.PerformanceFunds = e.Elements("FundGroup").Select(f => { List<Fund> funds = (from fund in e.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList(); string heading = (e.Attribute("heading") == null) ? "" : (string)e.Attribute("heading"); }).ToDictionary(xx => heading, xx => Funds); return control; }).ToList(); Could someone point me in the right direction please? I'm not even sure if 'Expression' is the right terminology. Could someone fill me in on that too? Thanks.

    Read the article

  • linq and contains

    - by kusanagi
    i have func public PageOfList<ConsaltQuestion> Filter(int? type, int pageId, EntityCollection<ConsaltCost> ConsaltRoles) { // return _dataContext.ConsaltQuestion.Where((o => o.Type == type || type == null) && (o=>o.Paid == paid)); return (from i in _dataContext.ConsaltQuestion where ((i.Type == type || type == null) && (i.Paid == true) && (ConsaltRoles.Contains(ConsaltCostDetails(i.Type.Value)))) select i).ToList().ToPageOfList(pageId, 20); } it return error LINQ to Entities does not recognize the method 'Boolean Contains(mrhome.Models.ConsaltCost)' method, and this method cannot be translated into a store expression. how can i fix it?

    Read the article

  • AutoMapper and Linq expression.

    - by Raffaeu
    I am exposing the Dto generated from AutoMapper to my WCF services. I would like to offer something like that from WCF: IList GetPersonByQuery(Expression predicate); Unfortunately I need back an expression tree of Person as my DAL doesn't know the DTO. I am trying this wihtout success: var func = new Func<Person, bool>(x => x.FirstName.Contains("John")); var funcDto = Mapper.Map<Func<Person, bool>, Func<PersonDto, bool>>(func); Console.WriteLine(func.ToString()); Console.WriteLine(funcDto.ToString()); THe error that I get is: ----> System.ArgumentException : Type 'System.Func`2[TestAutoMapper.PersonDto,System.Boolean]' does not have a default constructor Do you have any suggestions?

    Read the article

  • Strange LINQ to SQL Behavior

    - by mcass20
    What is wrong with the last query? Is it a bug or am I missing something? This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>David</value>%")); This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%David%</value>%")); This query returns 0 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>av</value>%")); This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%av%</value>%")); This query returns 0 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>v</value>%")); This query returns 15 records (incorrect, should return 2): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%v%</value>%"));

    Read the article

  • Linq - reuse expression on child property

    - by user175528
    Not sure if what I am trying is possible or not, but I'd like to reuse a linq expression on an objects parent property. With the given classes: class Parent { int Id { get; set; } IList<Child> Children { get; set; } string Name { get; set; } } class Child{ int Id { get; set; } Parent Dad { get; set; } string Name { get; set; } } If i then have a helper Expression<Func<Parent,bool> ParentQuery() { Expression<Func<Parent,bool> q = p => p.Name=="foo"; } I then want to use this when querying data out for a child, along the lines of: using(var context=new Entities.Context) { var data=context.Child.Where(c => c.Name=="bar" && c.Dad.Where(ParentQuery)); } I know I can do that on child collections: using(var context=new Entities.Context) { var data=context.Parent.Where(p => p.Name=="foo" && p.Childen.Where(childQuery)); } but cant see any way to do this on a property that isnt a collection. This is just a simplified example, actually the ParentQuery will be more complex and I want to avoid having this repeated in multiple places as rather than just having 2 layers I'll have closer to 5 or 6, but all of them will need to reference the parent query to ensure security.

    Read the article

  • VB.NET logical expression evaluator

    - by Tim
    I need to test a logical expression held in a string to see if it evaluate to TRUE or FALSE.(the strig is built dynamically) For example the resulting string may contain "'dog'<'cat' OR (14 AND 4<6)". There are no variables in the string, it will logically evaluate. It will only contain simple operators = < < = <= and AND , OR and Open and Close Brackets, string constants and numbers. (converted to correct syntax && || etc.) I currently acheive this by creating a jscipt function and compiling it into a .dll. I then reference the .dll in my VB.NET project. class ExpressionEvaluator { function Evaluate(Expression : String) { return eval(Expression); } } Is there a simpler method using built in .NET functions or Lamdba expressions.

    Read the article

  • How to create a function and pass in variable length argument list?

    - by Jian Lin
    We can create a function p in the following code: var p = function() { }; if (typeof(console) != 'undefined' && console.log) { p = function() { console.log(arguments); }; } but the arguments are passed like an array to console.log, instead of passed one by one as in console.log(arguments[0], arguments[1], arguments[2], ... Is there a way to expand the arguments and pass to console.log like the way above? Note that if the original code were var p = function() { }; if (typeof(console) != 'undefined' && console.log) { p = console.log; } then it works well on Firefox and IE 8 but not on Chrome.

    Read the article

  • Using deprecated binders and C++0x lambdas

    - by Sumant
    C++0x has deprecated the use of old binders such as bind1st and bind2nd in favor of generic std::bind. C++0x lambdas bind nicely with std::bind but they don't bind with classic bind1st and bind2nd because by default lambdas don't have nested typedefs such as argument_type, first_argument_type, second_argument_type, and result_type. So I thought std::function can serve as a standard way to bind lambdas to the old binders because it exposes the necessary typedefs. However, using std::function is hard to use in this context because it forces you to spell out the function-type while instantiating it. auto bound = std::bind1st(std::function<int (int, int)>([](int i, int j){ return i < j; }), 10); // hard to use auto bound = std::bind1st(std::make_function([](int i, int j){ return i < j; }), 10); // nice to have but does not compile. I could not find a convenient object generator for std::function. Something like std::make_fuction would be nice to have. Does such a thing exist? If not, is there any other better way of binding lamdas to the classic binders?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >