Search Results

Search found 2455 results on 99 pages for 'lambda expressions'.

Page 9/99 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How to stop ReSharper from showing error on a lambda expression where Action is expected?

    - by carlmon
    In Silverlight, System.Windows.Threading's Dispatcher.BeginInvoke() takes an Action<T> or a delegate to invoke. .NET allows me to pass just the lambda expression. but ReSharper sees it as an error, saying "Cannot resolve method 'BeginInvoke(lambda expression)'": Dispatcher.BeginInvoke(() => { DoSomething(); }) The error goes away if I explicitly create the Action around the expression like this: Dispatcher.BeginInvoke(new Action<object>(o => { DoSomething(); })); I prefer the least amount of code in this case for the best readability. Is there a way to disable this specific ReSharper error notification? I tried some of the options, but could not find it. Thanks, Carl

    Read the article

  • What can procs and lambdas do that functions can't in ruby

    - by SecurityGate
    I've been working in Ruby for the last couple weeks, and I've come to the subject of procs, lambdas and blocks. After reading a fair share of examples from a variety of sources, I don't how they're much different from small, specialized functions. It's entirely possible that the examples I've read aren't showing the power behind procs and lambdas. def zero_function(x) x = x.to_s if x.length == 1 return x = "0" + x else return x end end zero_lambda = lambda {|x| x = x.to_s if x.length == 1 return x = "0" + x else return x end } zero_proc = Proc.new {|x| x = x.to_s if x.length == 1 puts x = "0" + x else puts x end } puts zero_function(4) puts zero_lambda.call(3) zero_proc.call(2) This function, proc, and lambda do the exact same thing, just slightly different. Is there any reason to choose one over another?

    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 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

  • Databinder.Eval using Lamda Expressions

    Using lambda expression to help with compile time checking of Eval statements...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Text editor capable of running complex Regular Expressions?

    - by Mashimom
    I want to find a text editor capable of running and mainly storing regular expressions for later re-use. It should also be able to run them across multiple files. I know I can get all that with grep, but there is not much for re-use on it. I was able to get some regular expression functionality on Gedit with plugins, but not nearly close to my needs. There is EditPad Pro for Windows (runs on wine) but native is always better :)

    Read the article

  • What are known approaches to graphing algebraic expressions?

    - by jeremynealbrown
    I am planning to build an expression parser that will be used to graph algebraic functions ( think TI-83 ) with JavaScript. Functions will take the form of f(x)= Aside from typical operators such as: + - * / ^ I'd also like to add support for inline functions such as: sin(), cos(), log() and random(). I have looked at implementing the Shunting Yard algorithm for parsing expressions, but it does not look like an efficient approach to evaluating a function with a hundreds or thousands of inputs. What other known algorithms exist for this task?

    Read the article

  • How can I use external expressions in Linq with EF4 (and LINQKit)?

    - by neo
    I want to separate out often used expressions in linq queries. I'm using Entity Framework 4 and also LINQKit but I still don't know how I should do it the right way. Let me give you an example: Article article = dataContainer.Articles.FirstOrDefault(a => a.Id == id); IEnumerable<Comment> comments = (from c in container.Comments where CommentExpressions.IsApproved.Invoke(c) select c); public static class CommentExpressions { public static Expression<Func<Module, bool>> IsApproved { get { return m => m.IsApproved; } } } Of course the IsApproved expression would be something much more complicated. The problem is that the Invoke() won't work because I didn't call .asExpandable() from LINQKit on container.Comments but I can't call it because it's just an ICollection instead of an ObjectSet. So my question is: Do I always have to go through the data context when I want to include external expressions or can I somehow use it on the object I fetched (Article)? Any ideas or best practices? Thanks very much! neo

    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

  • Can a class inherit from LambdaExpression in .NET? Or is this not recommended?

    - by d.
    Consider the following code (C# 4.0): public class Foo : LambdaExpression { } This throws the following design-time error: Foo does not implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) There's absolutely no problem with public class Foo : Expression { } but, out of curiosity and for the sake of learning, I've searched in Google System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) and guess what: zero results returned (when was the last time you saw that?). Needless to say, I haven't found any documentation on this method anywhere else. As I said, one can easily inherit from Expression; on the other hand LambdaExpression, while not marked as sealed (Expression<TDelegate> inherits from it), seems to be designed to prevent inheriting from it. Is this actually the case? Does anyone out there know what this method is about? EDIT (1): More info based on the first answers - If you try to implement Accept, the editor (C# 2010 Express) automatically gives you the following stub: protected override Expression Accept(System.Linq.Expressions.ExpressionVisitor visitor) { return base.Accept(visitor); } But you still get the same error. If you try to use a parameter of type StackSpiller directly, the compiler throws a different error: System.Linq.Expressions.Compiler.StackSpiller is inaccessible due to its protection level. EDIT (2): Based on other answers, inheriting from LambdaExpression is not possible so the question as to whether or not it is recommended becomes irrelevant. I wonder if, in cases like this, the error message should be Foo cannot implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) because [reasons go here]; the current error message (as some answers prove) seems to tell me that all I need to do is implement Accept (which I can't do).

    Read the article

  • Some Original Expressions

    - by Phil Factor
    Guest Editorial for Simple-Talk newsletterIn a guest editorial for the Simple-Talk Newsletter, Phil Factor wonders if we are still likely to find some more novel and unexpected ways of using the newer features of Transact SQL: or maybe in some features that have always been there! There can be a great deal of fun to be had in trying out recent features of SQL Expressions to see if  they provide new functionality.  It is surprisingly rare to find things that couldn’t be done before, but in a different   and more cumbersome way; but it is great to experiment or to read of someone else making that discovery.  One such recent feature is the ‘table value constructor’, or ‘VALUES constructor’, that managed to get into SQL Server 2008 from Standard SQL.  This allows you to create derived tables of up to 1000 rows neatly within select statements that consist of  lists of row values.  E.g. SELECT Old_Welsh, number FROM (VALUES ('Un',1),('Dou',2),('Tri',3),('Petuar',4),('Pimp',5),('Chwech',6),('Seith',7),('Wyth',8),('Nau',9),('Dec',10)) AS WelshWordsToTen (Old_Welsh, number) These values can be expressions that return single values, including, surprisingly, subqueries. You can use this device to create views, or in the USING clause of a MERGE statement. Joe Celko covered  this here and here.  It can become extraordinarily handy to use once one gets into the way of thinking in these terms, and I’ve rewritten a lot of routines to use the constructor, but the old way of using UNION can be used the same way, but is a little slower and more long-winded. The use of scalar SQL subqueries as an expression in a VALUES constructor, and then applied to a MERGE, has got me thinking. It looks very clever, but what use could one put it to? I haven’t seen anything yet that couldn’t be done almost as  simply in SQL Server 2000, but I’m hopeful that someone will come up with a way of solving a tricky problem, just in the same way that a freak of the XML syntax forever made the in-line  production of delimited lists from an expression easy, or that a weird XML pirouette could do an elegant  pivot-table rotation. It is in this sort of experimentation where the community of users can make a real contribution. The dissemination of techniques such as the Number, or Tally table, or the unconventional ways that the UPDATE statement can be used, has been rapid due to articles and blogs. However, there is plenty to be done to explore some of the less obvious features of Transact SQL. Even some of the features introduced into SQL Server 2000 are hardly well-known. Certain operations on data are still awkward to perform in Transact SQL, but we mustn’t, I think, be too ready to state that certain things can only be done in the application layer, or using a CLR routine. With the vast array of features in the product, and with the tools that surround it, I feel that there is generally a way of getting tricky things done. Or should we just stick to our lasts and push anything difficult out into procedural code? I’d love to know your views.

    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

  • Editing XML Literals Embedded Expressions in Visual Basic 2010 (Avner Aharoni)

    The implicit line continuation feature in Visual Basic 2010 provided an opportunity to improve the code editing experience in XML literals embedded expressions. In Visual Studio 2008, pressing Enter inside an embedded expression would result in the cursor being positioned to the left of the end embedded expression tag. In Visual Studio 2010, pressing Enter inserts a newline for the cursor, and the end embedded expression tag moves to the line below. This minimizes the number of key strokes needed...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Algorithm to match list of regular expressions

    - by DSII
    I have two algorithmic questions for a project I am working on. I have thought about these, and have some suspicions, but I would love to hear the community's input as well. Suppose I have a string, and a list of N regular expressions (actually they are wildcard patterns representing a subset of full regex functionality). I want to know whether the string matches at least one of the regular expressions in the list. Is there a data structure that can allow me to match the string against the list of regular expressions in sublinear (presumably logarithmic) time? This is an extension of the previous problem. Suppose I have the same situation: a string and a list of N regular expressions, only now each of the regular expressions is paired with an offset within the string at which the match must begin (or, if you prefer, each of the regular expressions must match a substring of the given string beginning at the given offset). To give an example, suppose I had the string: This is a test string and the regex patterns and offsets: (a) his.* at offset 0 (b) his.* at offset 1 The algorithm should return true. Although regex (a) does not match the string beginning at offset 0, regex (b) does match the substring beginning at offset 1 ("his is a test string"). Is there a data structure that can allow me to solve this problem in sublinear time? One possibly useful piece of information is that often, many of the offsets in the list of regular expressions are the same (i.e. often we are matching the substring at offset X many times). This may be useful to leverage the solution to problem #1 above. Thank you very much in advance for any suggestions you may have!

    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

  • 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

  • ASP.NET 4.0- Html Encoded Expressions

    - by Jalpesh P. Vadgama
    We all know <%=expression%> features in asp.net. We can print any string on page from there. Mostly we are using them in asp.net mvc. Now we have one new features with asp.net 4.0 that we have HTML Encoded Expressions and this prevent Cross scripting attack as we are html encoding them. ASP.NET 4.0 introduces a new expression syntax <%: expression %> which automatically convert string into html encoded. Let’s take an example for that. I have just created an hello word protected method which will return a simple string which contains characters that needed to be HTML Encoded. Below is code for that. protected static string HelloWorld() { return "Hello World!!! returns from function()!!!>>>>>>>>>>>>>>>>>"; } Now let’s use the that hello world in our page html like below. I am going to use both expression to give you exact difference. <form id="form1" runat="server"> <div> <strong><%: HelloWorld()%></strong> </div> <div> <strong><%= HelloWorld()%></strong> </div> </form> Now let’s run the application and you can see in browser both look similar. But when look into page source html in browser like below you can clearly see one is HTML Encoded and another one is not. That’s it.. It’s cool.. Stay tuned for more.. Happy Programming Technorati Tags: ASP.NET 4.0,HTMLEncode,C#4.0

    Read the article

  • How can I combine several Expressions into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method. UPDATE So, whilst it appears that there is no way to do this directly in C#3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit?

    Read the article

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