Search Results

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

Page 7/39 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Using LINQ Lambda Expressions to Design Customizable Generic Components

    LINQ makes code easier to write and maintain by abstracting the data source. It provides a uniform way to handle widely diverse data structures within an application. LINQ’s Lambda syntax is clever enough to even allow you to create generic building blocks with hooks, into which you can inject arbitrary functions. Michael Sorens explains, and demonstrates with examples. span.fullpost {display:none;}

    Read the article

  • Using LINQ Lambda Expressions to Design Customizable Generic Components

    LINQ makes code easier to write and maintain by abstracting the data source. It provides a uniform way to handle widely diverse data structures within an application. LINQ’s Lambda syntax is clever enough even to allow you to create generic building blocks with hooks into which you can inject arbitrary functions. Michael Sorens explains, and demonstrates with examples.

    Read the article

  • Are lambda expressions/delegates in C# "pure", or can they be?

    - by Bob
    I recently asked about functional programs having no side effects, and learned what this means for making parallelized tasks trivial. Specifically, that "pure" functions make this trivial as they have no side effects. I've also recently been looking into LINQ and lambda expressions as I've run across examples many times here on StackOverflow involving enumeration. That got me to wondering if parallelizing an enumeration or loop can be "easier" in C# now. Are lambda expressions "pure" enough to pull off trivial parallelizing? Maybe it depends on what you're doing with the expression, but can they be pure enough? Would something like this be theoretically possible/trivial in C#?: Break the loop into chunks Run a thread to loop through each chunk Run a function that does something with the value from the current loop position of each thread For instance, say I had a bunch of objects in a game loop (as I am developing a game and was thinking about the possibility of multiple threads) and had to do something with each of them every frame, would the above be trivial to pull off? Looking at IEnumerable it seems it only keeps track of the current position, so I'm not sure I could use the normal generic collections to break the enumeration into "chunks". Sorry about this question. I used bullets above instead of pseudo-code because I don't even know enough to write pseudo-code off the top of my head. My .NET knowledge has been purely simple business stuff and I'm new to delegates and threads, etc. I mainly want to know if the above approach is good for pursuing, and if delegates/lambdas don't have to be worried about when it comes to their parallelization.

    Read the article

  • .Net lambda expression-- where did this parameter come from?

    - by larryq
    I'm a lambda newbie, so if I'm missing vital information in my description please tell me. I'll keep the example as simple as possible. I'm going over someone else's code and they have one class inheriting from another. Here's the derived class first, along with the lambda expression I'm having trouble understanding: class SampleViewModel : ViewModelBase { private ICustomerStorage storage = ModelFactory<ICustomerStorage>.Create(); public ICustomer CurrentCustomer { get { return (ICustomer)GetValue(CurrentCustomerProperty); } set { SetValue(CurrentCustomerProperty, value); } } private int quantitySaved; public int QuantitySaved { get { return quantitySaved; } set { if (quantitySaved != value) { quantitySaved = value; NotifyPropertyChanged(p => QuantitySaved); //where does 'p' come from? } } } public static readonly DependencyProperty CurrentCustomerProperty; static SampleViewModel() { CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(ICustomer), typeof(SampleViewModel), new UIPropertyMetadata(ModelFactory<ICustomer>.Create())); } //more method definitions follow.. Note the call to NotifyPropertyChanged(p => QuantitySaved) bit above. I don't understand where the "p" is coming from. Here's the base class: public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IXtremeMvvmViewModel { public event PropertyChangedEventHandler PropertyChanged; protected virtual void NotifyPropertyChanged<T>(Expression<Func<ViewModelBase, T>> property) { MvvmHelper.NotifyPropertyChanged(property, PropertyChanged); } } There's a lot in there that's not germane to the question I'm sure, but I wanted to err on the side of inclusiveness. The problem is, I don't understand where the 'p' parameter is coming from, and how the compiler knows to (evidently?) fill in a type value of ViewModelBase from thin air? For fun I changed the code from 'p' to 'this', since SampleViewModel inherits from ViewModelBase, but I was met with a series of compiler errors, the first one of which statedInvalid expression term '=>' This confused me a bit since I thought that would work. Can anyone explain what's happening here?

    Read the article

  • Issues with ILMerge, Lambda Expressions and VS2010 merging?

    - by John Blumenauer
    A little Background For quite some time now, it’s been possible to merge multiple .NET assemblies into a single assembly using ILMerge in Visual Studio 2008.  This is especially helpful when writing wrapper assemblies for 3rd-party libraries where it’s desirable to minimize the number of assemblies for distribution.  During the merge process, ILMerge will take a set of assemblies and merge them into a single assembly.  The resulting assembly can be either an executable or a DLL and is identified as the primary assembly. Issue During a recent project, I discovered using ILMerge to merge assemblies containing lambda expressions in Visual Studio 2010 is resulting in invalid primary assemblies.  The code below is not where the initial issue was identified, I will merely use it to illustrate the problem at hand. In order to describe the issue, I created a console application and a class library for calculating a few math functions utilizing lambda expressions.  The code is available for download at the bottom of this blog entry. MathLib.cs using System; namespace MathLib { public static class MathHelpers { public static Func<double, double, double> Hypotenuse = (x, y) => Math.Sqrt(x * x + y * y); static readonly Func<int, int, bool> divisibleBy = (int a, int b) => a % b == 0; public static bool IsPrimeNumber(int x) { { for (int i = 2; i <= x / 2; i++) if (divisibleBy(x, i)) return false; return true; }; } } } Program.cs using System; using MathLib; namespace ILMergeLambdasConsole { class Program { static void Main(string[] args) { int n = 19; if (MathHelpers.IsPrimeNumber(n)) { Console.WriteLine(n + " is prime"); } else { Console.WriteLine(n + " is not prime"); } Console.ReadLine(); } } } Not surprisingly, the preceding code compiles, builds and executes without error prior to running the ILMerge tool.   ILMerge Setup In order to utilize ILMerge, the following changes were made to the project. The MathLib.dll assembly was built in release configuration and copied to the MathLib folder.  The following folder hierarchy was used for this example:   The project file for ILMergeLambdasConsole project file was edited to add the ILMerge post-build configuration.  The following lines were added near the bottom of the project file:  <Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release'"> <Exec Command="&quot;..\..\lib\ILMerge\Ilmerge.exe&quot; /ndebug /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(ReferenceCopyLocalPaths->'&quot;%(FullPath)&quot;', ' ')" /> <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" /> </Target> The ILMergeLambdasConsole project was modified to reference the MathLib.dll located in the MathLib folder above. ILMerge and ILMerge.exe.config was copied into the ILMerge folder shown above.  The contents of ILMerge.exe.config are: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/> </startup> </configuration> Post-ILMerge After compiling and building, the MathLib.dll assembly will be merged into the ILMergeLambdasConsole executable.  Unfortunately, executing ILMergeLambdasConsole.exe now results in a crash.  The ILMerge documentation recommends using PEVerify.exe to validate assemblies after merging.  Executing PEVerify.exe against the ILMergeLambdasConsole.exe assembly results in the following error:    Further investigation by using Reflector reveals the divisibleBy method in the MathHelpers class looks a bit questionable after the merge.     Prior to using ILMerge, the same divisibleBy method appeared as the following in Reflector: It’s pretty obvious something has gone awry during the merge process.  However, this is only occurring when building within the Visual Studio 2010 environment.  The same code and configuration built within Visual Studio 2008 executes fine.  I’m still investigating the issue.  If anyone has already experienced this situation and solved it, I would love to hear from you.  However, as of right now, it looks like something has gone terribly wrong when executing ILMerge against assemblies containing Lambdas in Visual Studio 2010. Solution Files ILMergeLambdaExpression

    Read the article

  • .NET: Best way to execute a lambda on UI thread after a delay?

    - by Scott Bussinger
    I had a situation come up that required running a lambda expression on the UI thread after a delay. I thought of several ways to do this and finally settled on this approach Task.Factory.StartNew(() => Thread.Sleep(1000)) .ContinueWith((t) => textBlock.Text="Done",TaskScheduler.FromCurrentSynchronizationContext()); But I'm wondering if there's an easier way that I missed. Any suggestions for a shorter, simpler or easier technique? Assume .NET 4 is available.

    Read the article

  • How to declare a function that accepts a lambda?

    - by Andreas Bonini
    I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions. For example: int main() { int test = 5; LambdaTest([&](int a) { test += a; }); return EXIT_SUCCESS; } How should I declare LambdaTest? What's the type of its first argument? And then, how can I call the anonymous function passing to it - for example - "10" as its argument?

    Read the article

  • Lambda expressions - set the value of one property in a collection of objects based on the value of

    - by Michael Rut
    I'm new to lambda expressions and looking to leverage the syntax to set the value of one property in a collection based on another value in a collection Typically I would do a loop: class item{ public string name {get;set;} public string value {get;set;} } class business { item item1 = new item(name="name1"); item item2 = new item(name="name2"); item item3 = new item(name="name3"); Collection<item> items = new Collection() {item1,item2,item3}; //This is what I want to simplify for( int i = 0; i < items.count; i++) { if(items[i].item.name == "name2") { //set the value items[i].item.value = "value2"; } } }

    Read the article

  • How do I use a Lambda expression to sort INTEGERS inside a object?

    - by punkouter
    I have a collection of objects and I know that I can sort by NAME (string type) by saying collEquipment.Sort((x, y) = string.Compare(x.ItemName, y.ItemName)); that WORKS. But I want to sort by a ID (integer type) and there is no such thing as Int32.Compare So how do I do this? This doesnt work collEquipment.Sort((x, y) = (x.ID < y.ID); //error I know the answer is going to be really simple. Lambda expressions confuse me.

    Read the article

  • How do I make lambda functions generic in Scala?

    - by Electric Coffee
    As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method... making the 'def' kind generic is fairly straight forward def someFunc[T](a: T) { // insert body here what I'm having trouble with here is how to make the following generic: val someFunc = (a: Int) => // insert body here of course right now a is an integer, but what would I need to do to make it generic? val someFunc[T] = (a: T) => doesn't work, neither does val someFunc = [T](a: T) => Is it even possible to make them generic, or should I just stick to the 'def' variant?

    Read the article

  • What is the easiest way to get the property value from a passed lambda expression in an extension me

    - by Andrew Siemer
    I am writing a dirty little extension method for HtmlHelper so that I can say something like HtmlHelper.WysiwygFor(lambda) and display the CKEditor. I have this working currently but it seems a bit more cumbersome than I would prefer. I am hoping that there is a more straight forward way of doing this. Here is what I have so far. public static MvcHtmlString WysiwygFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { return MvcHtmlString.Create(string.Concat("<textarea class=\"ckeditor\" cols=\"80\" id=\"", expression.MemberName(), "\" name=\"editor1\" rows=\"10\">", GetValue(helper, expression), "</textarea>")); } private static string GetValue<TModel, TProperty>(HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { MemberExpression body = (MemberExpression)expression.Body; string propertyName = body.Member.Name; TModel model = helper.ViewData.Model; string value = typeof(TModel).GetProperty(propertyName).GetValue(model, null).ToString(); return value; } private static string MemberName<T, V>(this Expression<Func<T, V>> expression) { var memberExpression = expression.Body as MemberExpression; if (memberExpression == null) throw new InvalidOperationException("Expression must be a member expression"); return memberExpression.Member.Name; } Thanks!

    Read the article

  • in sending with name using ? (counting), how does the process happen? [closed]

    - by sam
    Sometimes expressions has two states. the result of analyses might be two different things but at the end, there might be the same answer(result) for them.(the way we get to the answer is different,but the result is the same) for example: P-Q = M P-T = M in lambda we have two solutions. 1.sending with name. (in ALGOL it have over load) 2.sending with value Example: Q: (?y.(yy) (?x.(xx)a)) 1.sending with name (?x.(xx)a ?x.(xx)a) ((aa)(aa)) 2.sending with value (?y.(yy) aa) ((aa)(aa)) now here is the question, in sending with name that used ? (counting), how does the process happen? How this sending (transmittal) happen? How does it work?

    Read the article

  • Help with boost::lambda expression

    - by Venkat Shivanandan
    I tried to write a function that calculates a hamming distance between two codewords using the boost lambda library. I have the following code: #include <iostream> #include <numeric> #include <boost/function.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/if.hpp> #include <boost/bind.hpp> #include <boost/array.hpp> template<typename Container> int hammingDistance(Container & a, Container & b) { return std::inner_product( a.begin(), a.end(), b.begin(), (_1 + _2), boost::lambda::if_then_else_return(_1 != _2, 1, 0) ); } int main() { boost::array<int, 3> a = {1, 0, 1}, b = {0, 1, 1}; std::cout << hammingDistance(a, b) << std::endl; } And the error I am getting is: HammingDistance.cpp: In function ‘int hammingDistance(Container&, Container&)’: HammingDistance.cpp:15: error: no match for ‘operator+’ in ‘<unnamed>::_1 + <unnamed>::_2’ HammingDistance.cpp:17: error: no match for ‘operator!=’ in ‘<unnamed>::_1 != <unnamed>::_2’ /usr/include/c++/4.3/boost/function/function_base.hpp:757: note: candidates are: bool boost::operator!=(boost::detail::function::useless_clear_type*, const boost::function_base&) /usr/include/c++/4.3/boost/function/function_base.hpp:745: note: bool boost::operator!=(const boost::function_base&, boost::detail::function::useless_clear_type*) This is the first time I am playing with boost lambda. Please tell me where I am going wrong. Thanks.

    Read the article

  • Mutating the expression tree of a predicate to target another type

    - by Jon
    Intro In the application I 'm currently working on, there are two kinds of each business object: the "ActiveRecord" type, and the "DataContract" type. So for example, we have: namespace ActiveRecord { class Widget { public int Id { get; set; } } } namespace DataContracts { class Widget { public int Id { get; set; } } } The database access layer takes care of "translating" between hierarchies: you can tell it to update a DataContracts.Widget, and it will magically create an ActiveRecord.Widget with the same property values and save that. The problem I have surfaced when attempting to refactor this database access layer. The Problem I want to add methods like the following to the database access layer: // Widget is DataContract.Widget interface DbAccessLayer { IEnumerable<Widget> GetMany(Expression<Func<Widget, bool>> predicate); } The above is a simple general-use "get" method with custom predicate. The only point of interest is that I 'm not passing in an anonymous function but rather an expression tree. This is done because inside DbAccessLayer we have to query ActiveRecord.Widget efficiently (LINQ to SQL) and not have the database return all ActiveRecord.Widget instances and then filter the enumerable collection. We need to pass in an expression tree, so we ask for one as the parameter for GetMany. The snag: the parameter we have needs to be magically transformed from an Expression<Func<DataContract.Widget, bool>> to an Expression<Func<ActiveRecord.Widget, bool>>. This is where I haven't managed to pull it off... Attempted Solution What we 'd like to do inside GetMany is: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( predicate.Body, predicate.Parameters); // use lambda to query ActiveRecord.Widget and return some value } This won't work because in a typical scenario, for example if: predicate == w => w.Id == 0; ...the expression tree contains a MemberAccessExpression instance which has a MemberInfo property (named Member) that point to members of DataContract.Widget. There are also ParameterExpression instances both in the expression tree and in its parameter expression collection (predicate.Parameters); After searching a bit, I found System.Linq.Expressions.ExpressionVisitor (its source can be found here in the context of a how-to, very helpful) which is a convenient way to modify an expression tree. Armed with this, I implemented a visitor. This simple visitor only takes care of changing the types in member access and parameter expressions. It may not be complete, but it's fine for the expression w => w.Id == 0. internal class Visitor : ExpressionVisitor { private readonly Func<Type, Type> dataContractToActiveRecordTypeConverter; public Visitor(Func<Type, Type> dataContractToActiveRecordTypeConverter) { this.dataContractToActiveRecordTypeConverter = dataContractToActiveRecordTypeConverter; } protected override Expression VisitMember(MemberExpression node) { var dataContractType = node.Member.ReflectedType; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); var converted = Expression.MakeMemberAccess( base.Visit(node.Expression), activeRecordType.GetProperty(node.Member.Name)); return converted; } protected override Expression VisitParameter(ParameterExpression node) { var dataContractType = node.Type; var activeRecordType = this.dataContractToActiveRecordTypeConverter(dataContractType); return Expression.Parameter(activeRecordType, node.Name); } } With this visitor, GetMany becomes: IEnumerable<DataContract.Widget> GetMany( Expression<Func<DataContract.Widget, bool>> predicate) { var visitor = new Visitor(...); var lambda = Expression.Lambda<Func<ActiveRecord.Widget, bool>>( visitor.Visit(predicate.Body), predicate.Parameters.Select(p => visitor.Visit(p)); var widgets = ActiveRecord.Widget.Repository().Where(lambda); // This is just for reference, see below Expression<Func<ActiveRecord.Widget, bool>> referenceLambda = w => w.Id == 0; // Here we 'd convert the widgets to instances of DataContract.Widget and // return them -- this has nothing to do with the question though. } Results The good news is that lambda is constructed just fine. The bad news is that it isn't working; it's blowing up on me when I try to use it (the exception messages are really not helpful at all). I have examined the lambda my code produces and a hardcoded lambda with the same expression; they look exactly the same. I spent hours in the debugger trying to find some difference, but I can't. When predicate is w => w.Id == 0, lambda looks exactly like referenceLambda. But the latter works with e.g. IQueryable<T>.Where, while the former does not (I have tried this in the immediate window of the debugger). I should also mention that when predicate is w => true, it all works just fine. Therefore I am assuming that I 'm not doing enough work in Visitor, but I can't find any more leads to follow on. Can someone point me in the right direction? Thanks in advance for your help!

    Read the article

  • C# going nuts when I declare variables with the same name as the ones in a lambda

    - by Rubys
    I have the following code (generates a quadratic function given the a, b, and c) Func<double, double, double, Func<double, double>> funcGenerator = (a, b, c) => f => f * f * a + b * f + c; Up until now, lovely. But then, if i try to declare a variable named a, b, c or f, visual studio pops a "A local variable named 'f' could not be declared at this scope because it would give a different meaning to 'f' which is used in a child scope." Basically, this fails, and I have no idea why, because a child scope doesn't even make any sense. Func funcGenerator = (a, b, c) = f = f * f * a + b * f + c; var f = 3; // Fails var d = 3; // Fine What's going on here?

    Read the article

  • How do I get around this lambda expression outer variable issue?

    - by panamack
    I'm playing with PropertyDescriptor and ICustomTypeDescriptor (still) trying to bind a WPF DataGrid to an object, for which the data is stored in a Dictionary. Since if you pass WPF DataGrid a list of Dictionary objects it will auto generate columns based on the public properties of a dictionary (Comparer, Count, Keys and Values) my Person subclasses Dictionary and implements ICustomTypeDescriptor. ICustomTypeDescriptor defines a GetProperties method which returns a PropertyDescriptorCollection. PropertyDescriptor is abstract so you have to subclass it, I figured I'd have a constructor that took Func and an Action parameters that delegate the getting and setting of the values in the dictionary. I then create a PersonPropertyDescriptor for each Key in the dictionary like this: foreach (string s in this.Keys) { var descriptor = new PersonPropertyDescriptor( s, new Func<object>(() => { return this[s]; }), new Action<object>(o => { this[s] = o; })); propList.Add(descriptor); } The problem is that each property get's its own Func and Action but they all share the outer variable s so although the DataGrid autogenerates columns for "ID","FirstName","LastName", "Age", "Gender" they all get and set against "Gender" which is the final resting value of s in the foreach loop. How can I ensure that each delegate uses the desired dictionary Key, i.e. the value of s at the time the Func/Action is instantiated? Much obliged. Here's the rest of my idea, I'm just experimenting here these are not 'real' classes... // DataGrid binds to a People instance public class People : List<Person> { public People() { this.Add(new Person()); } } public class Person : Dictionary<string, object>, ICustomTypeDescriptor { private static PropertyDescriptorCollection descriptors; public Person() { this["ID"] = "201203"; this["FirstName"] = "Bud"; this["LastName"] = "Tree"; this["Age"] = 99; this["Gender"] = "M"; } //... other ICustomTypeDescriptor members... public PropertyDescriptorCollection GetProperties() { if (descriptors == null) { var propList = new List<PropertyDescriptor>(); foreach (string s in this.Keys) { var descriptor = new PersonPropertyDescriptor( s, new Func<object>(() => { return this[s]; }), new Action<object>(o => { this[s] = o; })); propList.Add(descriptor); } descriptors = new PropertyDescriptorCollection(propList.ToArray()); } return descriptors; } //... other other ICustomTypeDescriptor members... } public class PersonPropertyDescriptor : PropertyDescriptor { private Func<object> getFunc; private Action<object> setAction; public PersonPropertyDescriptor(string name, Func<object> getFunc, Action<object> setAction) : base(name, null) { this.getFunc = getFunc; this.setAction = setAction; } // other ... PropertyDescriptor members... public override object GetValue(object component) { return getFunc(); } public override void SetValue(object component, object value) { setAction(value); } }

    Read the article

  • lambda expressions in VB.NET... what am I doing wrong???

    - by Bob
    when I run this C# code, no problems... but when I translate it into VB.NET it compiles but blows due to 'CompareString' member not being allowed in the expression... I feel like I'm missing something key here... private void PrintButton_Click(object sender, EventArgs e) { if (ListsListBox.SelectedIndex > -1) { //Context using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(UrlTextBox.Text)) { //Get selected list string listTitle = ListsListBox.SelectedItem.ToString(); ClientOM.Web site = ctx.Web; ctx.Load(site, s => s.Lists.Where(l => l.Title == listTitle)); ctx.ExecuteQuery(); ClientOM.List list = site.Lists[0]; //Get fields for this list ctx.Load(list, l => l.Fields.Where(f => f.Hidden == false && (f.CanBeDeleted == true || f.InternalName == "Title"))); ctx.ExecuteQuery(); //Get items for the list ClientOM.ListItemCollection listItems = list.GetItems( ClientOM.CamlQuery.CreateAllItemsQuery()); ctx.Load(listItems); ctx.ExecuteQuery(); // DOCUMENT CREATION CODE GOES HERE } MessageBox.Show("Document Created!"); } } but in VB.NET code this errors due to not being allowed 'CompareString' members in the ctx.Load() methods... Private Sub PrintButton_Click(sender As Object, e As EventArgs) If ListsListBox.SelectedIndex > -1 Then 'Context Using ctx As New ClientOM.ClientContext(UrlTextBox.Text) 'Get selected list Dim listTitle As String = ListsListBox.SelectedItem.ToString() Dim site As ClientOM.Web = ctx.Web ctx.Load(site, Function(s) s.Lists.Where(Function(l) l.Title = listTitle)) ctx.ExecuteQuery() Dim list As ClientOM.List = site.Lists(0) 'Get fields for this list ctx.Load(list, Function(l) l.Fields.Where(Function(f) f.Hidden = False AndAlso (f.CanBeDeleted = True OrElse f.InternalName = "Title"))) ctx.ExecuteQuery() 'Get items for the list Dim listItems As ClientOM.ListItemCollection = list.GetItems(ClientOM.CamlQuery.CreateAllItemsQuery()) ctx.Load(listItems) ' DOCUMENT CREATION CODE GOES HERE ctx.ExecuteQuery() End Using MessageBox.Show("Document Created!") End If End Sub

    Read the article

  • Can a lambda can be used to change a List's values in-place ( without creating a new list)?

    - by Saint Hill
    I am trying to determine the correct way of transforming all the values in a List using the new lambdas feature in the upcoming release of Java 8 without creating a **new** List. This pertains to times when a List is passed in by a caller and needs to have a function applied to change all the contents to a new value. For example, the way Collections.sort(list) changes a list in-place. What is the easiest way given this transforming function and this starting list: String function(String s){ return [some change made to value of s]; } List<String> list = Arrays.asList("Bob", "Steve", "Jim", "Arbby"); The usual way of applying a change to all the values in-place was this: for (int i = 0; i < list.size(); i++) { list.set(i, function( list.get(i) ); } Does lambdas and Java 8 offer: an easier and more expressive way? a way to do this without setting up all the scaffolding of the for(..) loop?

    Read the article

  • Why can't c# use inline anonymous lambdas or delegates?

    - by Samuel Meacham
    I hope I worded the title of my question appropriately. In c# I can use lambdas (as delegates), or the older delegate syntax to do this: Func<string> fnHello = () => "hello"; Console.WriteLine(fnHello()); Func<string> fnHello2 = delegate() { return "hello 2"; }; Console.WriteLine(fnHello2()); So why can't I "inline" the lambda or the delegate body, and avoid capturing it in a named variable (making it anonymous)? // Inline anonymous lambda not allowed Console.WriteLine( (() => "hello inline lambda")() ); // Inline anonymous delegate not allowed Console.WriteLine( (delegate() { return "hello inline delegate"; })() ); An example that works in javascript (just for comparison) is: alert( (function(){ return "hello inline anonymous function from javascript"; })() ); Which produces the expected alert box. UPDATE: It seems you can have an inline anonymous lambda in C#, if you cast appropriately, but the amount of ()'s starts to make it unruly. // Inline anonymous lambda with appropriate cast IS allowed Console.WriteLine( ((Func<string>)(() => "hello inline anonymous lambda"))() ); Perhaps the compiler can't infer the sig of the anonymous delegate to know which Console.WriteLine() you're trying to call? Does anyone know why this specific cast is required?

    Read the article

  • Preffered lambda syntax?

    - by Roger Alsing
    I'm playing around a bit with my own C like DSL grammar and would like some oppinions. I've reserved the use of "(...)" for invocations. eg: foo(1,2); My grammar supports "trailing closures" , pretty much like Ruby's blocks that can be passed as the last argument of an invocation. Currently my grammar support trailing closures like this: foo(1,2) { //parameterless closure passed as the last argument to foo } or foo(1,2) [x] { //closure with one argument (x) passed as the last argument to foo print (x); } The reason why I use [args] instead of (args) is that (args) is ambigious: foo(1,2) (x) { } There is no way in this case to tell if foo expects 3 arguments (int,int,closure(x)) or if foo expects 2 arguments and returns a closure with one argument(int,int) - closure(x) So thats pretty much the reason why I use [] as for now. I could change this to something like: foo(1,2) : (x) { } or foo(1,2) (x) -> { } So the actual question is, what do you think looks best? [...] is somewhat wrist unfriendly. let x = [a,b] { } Ideas?

    Read the article

  • Preferred lambda syntax?

    - by Roger Alsing
    I'm playing around a bit with my own C like DSL grammar and would like some oppinions. I've reserved the use of "(...)" for invocations. eg: foo(1,2); My grammar supports "trailing closures" , pretty much like Ruby's blocks that can be passed as the last argument of an invocation. Currently my grammar support trailing closures like this: foo(1,2) { //parameterless closure passed as the last argument to foo } or foo(1,2) [x] { //closure with one argument (x) passed as the last argument to foo print (x); } The reason why I use [args] instead of (args) is that (args) is ambigious: foo(1,2) (x) { } There is no way in this case to tell if foo expects 3 arguments (int,int,closure(x)) or if foo expects 2 arguments and returns a closure with one argument(int,int) - closure(x) So thats pretty much the reason why I use [] as for now. I could change this to something like: foo(1,2) : (x) { } or foo(1,2) (x) -> { } So the actual question is, what do you think looks best? [...] is somewhat wrist unfriendly. let x = [a,b] { } Ideas?

    Read the article

  • Proc.new vs Lambda in Ruby

    - by piemesons
    Plese check this: def foo f = Proc.new { return "return from foo from inside proc" } f.call # control leaves foo here return "return from foo" end def bar f = lambda { return "return from lambda" } f.call # control does not leave bar here return "return from bar" end puts foo # prints "return from foo from inside proc" puts bar # prints "return from bar" Can anybody tell me what lambda is and what is Proc and whats the difference.

    Read the article

  • boost::function & boost::lambda - call site invocation & accessing _1 and _2 as the type

    - by John Dibling
    Sorry for the confusing title. Let me explain via code: #include <string> #include <boost\function.hpp> #include <boost\lambda\lambda.hpp> #include <iostream> int main() { using namespace boost::lambda; boost::function<std::string(std::string, std::string)> f = _1.append(_2); std::string s = f("Hello", "There"); std::cout << s; return 0; } I'm trying to use function to create a function that uses the labda expressions to create a new return value, and invoke that function at the call site, s = f("Hello", "There"); When I compile this, I get: 1>------ Build started: Project: hacks, Configuration: Debug x64 ------ 1>Compiling... 1>main.cpp 1>.\main.cpp(11) : error C2039: 'append' : is not a member of 'boost::lambda::lambda_functor<T>' 1> with 1> [ 1> T=boost::lambda::placeholder<1> 1> ] Using MSVC 9. My fundamental understanding of function and lambdas may be lacking. The tutorials and docs did not help so far this morning. How do I do what I'm trying to do?

    Read the article

  • How to construct LambdaExpression with conversion

    - by nerijus
    I need to sort in ajax response grid by column name. Column value is number stored as a string. Let's say some trivial class (in real-life situation there is no possibility to modify this class): class TestObject { public TestObject(string v) { this.Value = v; } public string Value { get; set; } } then simple test: [Test] public void LambdaConstructionTest() { var queryable = new List<TestObject> { new TestObject("5"), new TestObject("55"), new TestObject("90"), new TestObject("9"), new TestObject("09"), new TestObject("900"), }.AsQueryable(); var sortingColumn = "Value"; ParameterExpression parameter = Expression.Parameter(queryable.ElementType); MemberExpression property = Expression.Property(parameter, sortingColumn); //// tried this one: var c = Expression.Convert(property, typeof(double)); LambdaExpression lambda = Expression.Lambda(property, parameter); //// constructs: o=>o.Value var callExpression = Expression.Call(typeof (Double), "Parse", null, property); var methodCallExpression = Expression.Call( typeof(Queryable), "OrderBy", new[] { queryable.ElementType, property.Type }, queryable.Expression, Expression.Quote(lambda)); // works, but sorts by string values. //Expression.Quote(callExpression)); // getting: System.ArgumentException {"Quoted expression must be a lambda"} var querable = queryable.Provider.CreateQuery<TestObject>(methodCallExpression); // return querable; // <- this is the return of what I need. } Sorry for not being clear in my first post as @SLaks answer was correct but I do not know how to construct correct lambda expression in this case.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >