Search Results

Search found 128 results on 6 pages for 'lambdas'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • C#/.NET Little Wonders: Of LINQ and Lambdas - A Presentation

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Today I’m giving a brief beginner’s guide to LINQ and Lambdas at the St. Louis .NET User’s Group so I thought I’d post the presentation here as well.  I updated the presentation a bit as well as added some notes on the query syntax.  Enjoy! The C#/.NET Fundaments: Of Lambdas and LINQ Presentation Of Lambdas and LINQ View more presentations from BlackRabbitCoder   Technorati Tags: C#, CSharp, .NET, Little Wonders, LINQ, Lambdas

    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

  • A Trio of Presentations: Little Wonders, StyleCop, and LINQ/Lambdas

    - by James Michael Hare
    This week is a busy week for me.  First of all I’m giving another presentation on a LINQ/Lambda primer for the rest of the developers in my company.  Of Lambdas and LINQ View more presentations from BlackRabbitCoder Then this Saturday the 25th of June I’ll be reprising my Little Wonders presentation for the Kansas City Developers Camp.  If you are in the area I highly recommend attending and seeing the other great presentations as well.  Their link is here. Little Wonders View more presentations from BlackRabbitCoder Finally, this Monday the 27th I’ll be speaking at the Saint Louis .NET Users group, giving my Automating Code Standards Using StyleCop and FxCop presentation.  If you are in the Saint Louis area stop by!  There’s two other simultaneous presentations as well if they’re more suited to your interests.  The link for the SLDNUG is here. Automating C# Coding Standards using StyleCop and FxCop View more presentations from BlackRabbitCoder Tweet Technorati Tags: C#,.NET,LINQ,Lambda,StyleCop,FxCop,Little Wonders

    Read the article

  • Using Lambdas for return values in Rhino.Mocks

    - by PSteele
    In a recent StackOverflow question, someone showed some sample code they’d like to be able to use.  The particular syntax they used isn’t supported by Rhino.Mocks, but it was an interesting idea that I thought could be easily implemented with an extension method. Background When stubbing a method return value, Rhino.Mocks supports the following syntax: dependency.Stub(s => s.GetSomething()).Return(new Order()); The method signature is generic and therefore you get compile-time type checking that the object you’re returning matches the return value defined by the “GetSomething” method. You could also have Rhino.Mocks execute arbitrary code using the “Do” method: dependency.Stub(s => s.GetSomething()).Do((Func<Order>) (() => new Order())); This requires the cast though.  It works, but isn’t as clean as the original poster wanted.  They showed a simple example of something they’d like to see: dependency.Stub(s => s.GetSomething()).Return(() => new Order()); Very clean, simple and no casting required.  While Rhino.Mocks doesn’t support this syntax, it’s easy to add it via an extension method. The Rhino.Mocks “Stub” method returns an IMethodOptions<T>.  We just need to accept a Func<T> and use that as the return value.  At first, this would seem straightforward: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(factory()); return opts; } And this would work and would provide the syntax the user was looking for.  But the problem with this is that you loose the late-bound semantics of a lambda.  The Func<T> is executed immediately and stored as the return value.  At the point you’re setting up your mocks and stubs (the “Arrange” part of “Arrange, Act, Assert”), you may not want the lambda executing – you probably want it delayed until the method is actually executed and Rhino.Mocks plugs in your return value. So let’s make a few small tweaks: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(default(T)); // required for Rhino.Mocks on non-void methods opts.WhenCalled(mi => mi.ReturnValue = factory()); return opts; } As you can see, we still need to set up some kind of return value or Rhino.Mocks will complain as soon as it intercepts a call to our stubbed method.  We use the “WhenCalled” method to set the return value equal to the execution of our lambda.  This gives us the delayed execution we’re looking for and a nice syntax for lambda-based return values in Rhino.Mocks. Technorati Tags: .NET,Rhino.Mocks,Mocking,Extension Methods

    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

  • Weak event handler model for use with lambdas

    - by Benjol
    OK, so this is more of an answer than a question, but after asking this question, and pulling together the various bits from Dustin Campbell, Egor, and also one last tip from the 'IObservable/Rx/Reactive framework', I think I've worked out a workable solution for this particular problem. It may be completely superseded by IObservable/Rx/Reactive framework, but only experience will show that. I've deliberately created a new question, to give me space to explain how I got to this solution, as it may not be immediately obvious. There are many related questions, most telling you you can't use inline lambdas if you want to be able to detach them later: Weak events in .Net? Unhooking events with lambdas in C# Can using lambdas as event handlers cause a memory leak? How to unsubscribe from an event which uses a lambda expression? Unsubscribe anonymous method in C# And it is true that if YOU want to be able to detach them later, you need to keep a reference to your lambda. However, if you just want the event handler to detach itself when your subscriber falls out of scope, this answer is for you.

    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

  • An abundance of LINQ queries and expressions using both the query and method syntax.

    - by nikolaosk
    In this post I will be writing LINQ queries against an array of strings, an array of integers.Moreover I will be using LINQ to query an SQL Server database. I can use LINQ against arrays since the array of strings/integers implement the IENumerable interface. I thought it would be a good idea to use both the method syntax and the query syntax. There are other places on the net where you can find examples of LINQ queries but I decided to create a big post using as many LINQ examples as possible. We...(read more)

    Read the article

  • Code and Slides: Building the Account at a Glance ASP.NET MVC, EF Code First, HTML5, and jQuery Application

    - by dwahlin
    This presentation was given at the spring 2012 DevConnections conference in Las Vegas and is based on my Pluralsight course. The presentation shows how several different technologies including ASP.NET MVC, EF Code First, HTML5, jQuery, Canvas, SVG, JavaScript patterns, Ajax, and more can be integrated together to build a robust application. An example of the application in action is shown next: View more of my presentations here. The complete code (and associated SQL Server database) for the Account at a Glance application can be found here. Check out the full-length course on the topic at Pluralsight.com.

    Read the article

  • Fun with Lambdas

    - by Roman A. Taycher
    Not having them used them all that much I'm not quite sure all that lambdas/blocks can be used for (other than map/collect/do/lightweight local function syntax). If some people could post some interesting but somewhat understandable examples (with explanation). preferred languages for examples: python, smalltalk, haskell

    Read the article

  • Use LINQ and lambdas to put string in proper case

    - by Tobias Funke
    I have this function called ProperCase that takes a string, then converts the first letter in each word to uppercase. So ProperCase("john smith") will return "John Smith". Here is the code: public string ProperCase(string input) { var retVal = string.Empty; var words = input.Split(' '); foreach (var word in words) { if (word.Length == 1) { retVal += word.ToUpper(); } else if (word.Length > 1) { retVal += word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower(); } retVal += ' '; } if (retVal.Length > 0) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } This code workds perfectly, but I'm pretty sure I can do it more elegantly with LINQ and lambdas. Can some please show me how?

    Read the article

  • Adapting Map Iterators Using STL/Boost/Lambdas

    - by John Dibling
    Consider the following non-working code: typedef map<int, unsigned> mymap; mymap m; for( int i = 1; i < 5; ++i ) m[i] = i; // 'remove' all elements from map where .second < 3 remove(m.begin(), m.end(), bind2nd(less<int>(), 3)); I'm trying to remove elements from this map where .second < 3. This obviously isn't written correctly. How do I write this correctly using: Standard STL function objects & techniques Boost.Bind C++0x Lambdas I know I'm not eraseing the elements. Don't worry about that; I'm just simplifying the problem to solve.

    Read the article

  • Nested Lambdas in wxHaskell Library

    - by kunkelwe
    I've been trying to figure out how I can make staticText elements resize to fit their contents with wxHaskell. From what I can tell, this is the default behavior in wxWidgets, but the wxHaskell wrapper specifically disables this behavior. However, the library code that creates new elements has me very confused. Can anyone provide an explanation for what this code does? staticText :: Window a -> [Prop (StaticText ())] -> IO (StaticText ()) staticText parent props = feed2 props 0 $ initialWindow $ \id rect -> initialText $ \txt -> \props flags -> do t <- staticTextCreate parent id txt rect flags {- (wxALIGN_LEFT + wxST_NO_AUTORESIZE) -} set t props return t I know that feed2 x y f = f x y, and that the type signature of initialWindow is initialWindow :: (Id -> Rect -> [Prop (Window w)] -> Style -> a) -> [Prop (Window w)] -> Style -> a and the signature of initialText is initialText :: Textual w => (String -> [Prop w] -> a) -> [Prop w] -> a but I just can't wrap my head around all the lambdas.

    Read the article

  • C# ambiguity in Func + extension methods + lambdas

    - by Hobbes
    I've been trying to make my way through this article: http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx ... And something on page 1 made me uncomfortable. In particular, I was trying to wrap my head around the Compose<() function, and I wrote an example for myself. Consider the following two Func's: Func<double, double> addTenth = x => x + 0.10; Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%"; No problem! It's easy to understand what these two do. Now, following the example from the article, you can write a generic extension method to compose these functions, like so: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } } Fine. So now you can say: string x = toPercentString.Compose<double, double, string>(addTenth)(0.4); And you get the string "50%" So far, so good. But there's something ambiguous here. Let's say you write another extension method, so now you have two functions: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } public static Func<double, string> Compose<TInput, TFirstOutput, TLastOutput>(this Func<double, string> toPercentString, Func<double, double> addTenth) { return input => toPercentString(addTenth(input + 99999)); } } Herein is the ambiguity. Don't these two function have overlapping signatures? Yes. Does this even compile? Yes. Which one get's called? The second one (which clearly gives you the "wrong" result) gets called. If you comment out either function, it still compiles, but you get different results. It seems like nitpicking, but there's something that deeply offends my sensibilities here, and I can't put my finger on it. Does it have to do with extension methods? Does it have to do with lambdas? Or does it have to do with how Func< allows you to parameterize the return type? I'm not sure. I'm guessing that this is all addressed somewhere in the spec, but I don't even know what to Google to find this. Help!

    Read the article

  • Lambdas within Extension methods: Possible memory leak?

    - by Oliver
    I just gave an answer to a quite simple question by using an extension method. But after writing it down i remembered that you can't unsubscribe a lambda from an event handler. So far no big problem. But how does all this behave within an extension method?? Below is my code snipped again. So can anyone enlighten me, if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times? I would say no, cause the scope of the timer is limited within this function. So after leaving it no one else has a reference to this object. I'm just a little unsure, cause we're here within a static function in a static class. public static class LabelExtensions { public static Label BlinkText(this Label label, int duration) { Timer timer = new Timer(); timer.Interval = duration; timer.Tick += (sender, e) => { timer.Stop(); label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold); }; label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold); timer.Start(); return label; } }

    Read the article

  • Undefined symbols for C++0x lambdas?

    - by Austin Hyde
    I was just poking around into some new stuff in C++0x, when I hit a stumbling block: #include <list> #include <cstdio> using namespace std; template <typename T,typename F> void ForEach (list<T> l, F f) { for (typename list<T>::iterator it=l.begin();it!=l.end();++it) f(*it); } int main() { int arr[] = {1,2,3,4,5,6}; list<int> l (arr,arr+6); ForEach(l,[](int x){printf("%d\n",x);}); } does not compile. I get a load of undefined symbol errors. Here's make's output: i386-apple-darwin9-gcc-4.5.0 -std=c++0x -I/usr/local/include -o func main.cpp Undefined symbols: "___cxa_rethrow", referenced from: std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o "operator new(unsigned long)", referenced from: __gnu_cxx::new_allocator<std::_List_node<int> >::allocate(unsigned long, void const*) in ccPxxPwU.o "___gxx_personality_v0", referenced from: ___gxx_personality_v0$non_lazy_ptr in ccPxxPwU.o "___cxa_begin_catch", referenced from: std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o "operator delete(void*)", referenced from: __gnu_cxx::new_allocator<std::_List_node<int> >::deallocate(std::_List_node<int>*, unsigned long) in ccPxxPwU.o "___cxa_end_catch", referenced from: std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o "std::__throw_bad_alloc()", referenced from: __gnu_cxx::new_allocator<std::_List_node<int> >::allocate(unsigned long, void const*) in ccPxxPwU.o "std::_List_node_base::_M_hook(std::_List_node_base*)", referenced from: void std::list<int, std::allocator<int> >::_M_insert<int const&>(std::_List_iterator<int>, int const&&&) in ccPxxPwU.o ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [func] Error 1 Why is this not working?

    Read the article

  • Closure and nested lambdas in C++0x

    - by DanDan
    Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example: std::vector<int> c1; int v = 10; <--- I want to capture this variable std::for_each( c1.begin(), c1.end(), [v](int num) <--- This is fine... { std::vector<int> c2; std::for_each( c2.begin(), c2.end(), [v](int num) <--- error on this line, how do I recapture v? { // Do something }); });

    Read the article

  • VB to C# conversion incongruency with lambdas

    - by Jason
    I have a bit of code that I have been tasked with converting to C# from VB. A snippet of mine seems like it cannot be converted from one to the other, and if so, I just don't know how to do it and am getting a little frustrated. Here's some background: OrderForm is an abstract class, inherited by Invoice (and also PurchaseOrder). The following VB snippet works correctly: Dim Invs As List(Of OrderForm) = GetForms(theOrder.OrderID) .... Dim inv As Invoice = Invs.Find( Function(someInv As Invoice) thePO.SubPONumber = someInv.SubInvoiceNumber) In C#, the best I came to converting this is: List<OrderForm> Invs = GetForms(theOrder.OrderID); .... Invoice inv = Invs.Find( (Invoice someInv) => thePO.SubPONumber == someInv.SubInvoiceNumber); However, I get the following error when I do this: Cannot convert lambda expression to delegate type 'System.Predicate' because the parameter types do not match the delegate parameter types Is there any way to fix this without restructuring my whole codebase?

    Read the article

  • C# Events and Lambdas, alternative to null check?

    - by Eugarps
    Does anybody see any drawbacks? It should be noted that you can't remove anonymous methods from an event delegate list, I'm aware of that (actually that was the conceptual motivation for this). The goal here is an alternative to: if (onFoo != null) onFoo.Invoke(this, null); And the code: public delegate void FooDelegate(object sender, EventArgs e); public class EventTest { public EventTest() { onFoo += (p,q) => { }; } public FireFoo() { onFoo.Invoke(this, null); } public event FooDelegate onFoo; }

    Read the article

  • View Lambdas in Visual Studio Debugger

    - by Vaccano
    I have the a simple LinqToSQL statement that is not working. Something Like this: List<MyClass> myList = _ctx.DBList .Where(x => x.AGuidID == paramID) .Where(x => x.BBoolVal == false) .ToList(); I look at _ctx.DBList in the debugger and the second item fits both parameters. Is there a way I can dig into this more to see what is going wrong?

    Read the article

  • Why lambdas seem broken in multithreaded environments (or how closures in C# works).

    Ive been playing around with some code for.NET 3.5 to enable us to split big operations into small parallel tasks. During this work I was reminded why Resharper has the Access to modified closure warning. This warning tells us about a inconsistency in handling the Immutable loop variable created in a foreach loop when lambdas [...]...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

  • C++0x and the Lack of Polymorphic Lambdas - Why?

    - by Dominar
    I've been reviewing the draft version of the upcoming C++0x standard. Specifically the section on lambdas, and am confused as to the reasoning for not introducing polymorphic lambdas. I had hoped we could use code such as the following: template<typename Container> void foo(Container c) { for_each(c.begin(),c.end(),[](T& t) { ++t; }); } What were the reasons: Was it the committee ran out of time? That polymorphic lambdas are too hard to implement? Or perhaps that they are seen as not being needed by the PTB?

    Read the article

1 2 3 4 5 6  | Next Page >