Search Results

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

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

  • List<object>.RemoveAll - How to create an appropriate Predicate

    - by CJM
    This is a bit of noob question - I'm still fairly new to C# and generics and completely new to predicates, delegates and lamda expressions... I have a class 'Enquiries' which contains a generic list of another class called 'Vehicles'. I'm building up the code to add/edit/delete Vehicles from the parent Enquiry. And at the moment, I'm specifically looking at deletions. From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID or all items with a particular EnquiryID. My problem is understanding how to feed .RemoveAll the right predicate - the examples I have seen are too simplistic (or perhaps I am too simplistic given my lack of knowledge of predicates, delegates and lambda expressions). So if I had a List<Of Vehicle> Vehicles where each Vehicle had an EnquiryID, how would I use Vehicles.RemoveAll() to remove all vehicles for a given EnquiryID? I understand there are several approaches to this so I'd be keen to hear the differences between approaches - as much as I need to get something working, this is also a learning exercise. As an supplementary question, is a Generic list the best repository for these objects? My first inclination was towards a Collection, but it appears I am out of date. Certainly Generics seem to be preferred, but I'm curious as to other alternatives. Thanks

    Read the article

  • PHP: passing a function with parameters as parameter

    - by Oden
    Hey, I'm not sure that silly question, but I ask: So, if there is an anonymous function I can give it as another anonymous functions parameter, if it has been already stored a variable. But, whats in that case, if I have stored only one function in a variable, and add the second directly as a parameter into it? Can I add parameters to the non-stored function? Fist example (thats what i understand :) ): $func = function($str){ return $str; }; $func2 = function($str){ return $str; }; $var = $func($func2('asd')); var_dump($var); // prints out string(3) "asd" That makes sense for me, but what is with the following one? $func = function($str){ return $str; }; $var = $func(function($str = "asd"){ return $str; }); var_dump($var); /** This prints out: object(Closure)#1 (1) { ["parameter"]=> array(1) { ["$str"]=> string(10) "" } } But why? */ And at the end, can someone recommend me a book or an article, from what i can learn this lambda coding feature of php? Thank you in advance for your answers :)

    Read the article

  • Are function-local typedefs visible inside C++0x lambdas?

    - by GMan - Save the Unicorns
    I've run into a strange problem. The following simplified code reproduces the problem in MSVC 2010 Beta 2: template <typename T> struct dummy { static T foo(void) { return T(); } }; int main(void) { typedef dummy<bool> dummy_type; auto x = [](void){ bool b = dummy_type::foo(); }; // auto x = [](void){ bool b = dummy<bool>::foo(); }; // works } The typedef I created locally in the function doesn't seem to be visible in the lambda. If I replace the typedef with the actual type, it works as expected. Here are some other test cases: // crashes the compiler, credit to Tarydon int main(void) { struct dummy {}; auto x = [](void){ dummy d; }; } // works as expected int main(void) { typedef int integer; auto x = [](void){ integer i = 0; }; } I don't have g++ 4.5 available to test it, right now. Is this some strange rule in C++0x, or just a bug in the compiler? From the results above, I'm leaning towards bug. Though the crash is definitely a bug. For now, I have filed two bug reports. All code snippets above should compile. The error has to do with using the scope resolution on locally defined scopes. (Spotted by dvide.) And the crash bug has to do with... who knows. :) Update According to the bug reports, they have both been fixed for the next release of Visual Studio 2010.

    Read the article

  • WPF DataGrid populating blank rows on TreeView's SelectedItemChanged

    - by jes9582
    When my DataGrid populates on the TreeView's SelectedItemChanged event it finds the objects and creates the rows accordingly but the rows populate with no text or are just blank. So I know it is finding my objects but it is not displaying them properly. Does anyone see where I made an error or suggest any changes or fixes? Thank you in advance! Here is the CSharp code that is setting the DataGrid's ItemsSource (I am using .dbml and LINQ with Lambda expressions): dgSystemSettings.ItemsSource = (tvSystemConfiguration.SelectedItem as SYSTEM_SETTINGS_GROUP).SYSTEM_SETTINGS_NAMEs.Join(ssdc.SYSTEM_SETTINGS_VALUEs, x => x.SSN_ID, y => y.SSV_SSN_ID, (x, y) => new { SYSTEM_SETTINGS_NAME = x, SYSTEM_SETTINGS_VALUE = y }); And here is the .xaml: <DataGrid Name="dgSystemSettings" AutoGenerateColumns="False" Height="447" Width="513" DockPanel.Dock="Right" ItemsSource="{Binding}" VerticalAlignment="Top" Margin="10,10,0,0"> <DataGrid.Columns> <DataGridTextColumn x:Name="colDisplayName" Header="Name" Binding="{Binding SSN_DISPLAY_NAME}"></DataGridTextColumn> <DataGridTextColumn x:Name="colValue" Header="Value" Binding="{Binding SSV_VALUE}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>

    Read the article

  • Rails scalar query

    - by Craig
    I need to display a UI element (e.g. a star or checkmark) for employees that are 'favorites' of the current user (another employee). The Employee model has the following relationship defined to support this: has_and_belongs_to_many :favorites, :class_name => "Employee", :join_table => "favorites", :association_foreign_key => "favorite_id", :foreign_key => "employee_id" The favorites has two fields: employee_id, favorite_id. If I were to write SQL, the following query would give me the results that I want: SELECT id, account, IF( ( SELECT favorite_id FROM favorites WHERE favorite_id=p.id AND employee_id = ? ) IS NULL, FALSE, TRUE) isFavorite FROM employees Where the '?' would be replaced by the session[:user_id]. How do I represent the isFavorite scalar query in Rails? Another approach would use a query like this: SELECT id, account, IF(favorite_id IS NULL, FALSE, TRUE) isFavorite FROM employees e LEFT OUTER JOIN favorites f ON e.id=f.favorite_id AND employee_id = ? Again, the '?' is replaced by the session[:user_id] value. I've had some success writing this in Rails: ee=Employee.find(:all, :joins=>"LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=1", :select=>"employees.*,favorites.favorite_id") Unfortunately, when I try to make this query 'dynamic' by replacing the '1' with a '?', I get errors. ee=Employee.find(:all, :joins=>["LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=?",1], :select=>"employees.*,favorites.favorite_id") Obviously, I have the syntax wrong, but can :joins expressions be 'dynamic'? Is this a case for a Lambda expression? I do hope to add other filters to this query and use it with will_paginate and acts_as_taggable_on, if that makes a difference. edit errors from trying to make :joins dynamic: ActiveRecord::ConfigurationError: Association named 'LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=?' was not found; perhaps you misspelled it? from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1906:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1911:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1910:in `each' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1910:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1830:in `initialize' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1789:in `new' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1789:in `add_joins!' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1686:in `construct_finder_sql' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1548:in `find_every' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:615:in `find'

    Read the article

  • Get the property, as a string, from an Expression<Func<TModel,TProperty>>

    - by Jaxidian
    I use some strongly-typed expressions that get serialized to allow my UI code to have strongly-typed sorting and searching expressions. These are of type Expression<Func<TModel,TProperty>> and are used as such: SortOption.Field = (p => p.FirstName);. I've gotten this working perfectly for this simple case. The code that I'm using for parsing the "FirstName" property out of there is actually reusing some existing functionality in a third-party product that we use and it works great, until we start working with deeply-nested properties(SortOption.Field = (p => p.Address.State.Abbreviation);). This code has some very different assumptions in the need to support deeply-nested properties. As for what this code does, I don't really understand it and rather than changing that code, I figured I should just write from scratch this functionality. However, I don't know of a good way to do this. I suspect we can do something better than doing a ToString() and performing string parsing. So what's a good way to do this to handle the trivial and deeply-nested cases? Requirements: Given the expression p => p.FirstName I need a string of "FirstName". Given the expression p => p.Address.State.Abbreviation I need a string of "Address.State.Abbreviation" While it's not important for an answer to my question, I suspect my serialization/deserialization code could be useful to somebody else who finds this question in the future, so it is below. Again, this code is not important to the question - I just thought it might help somebody. Note that DynamicExpression.ParseLambda comes from the Dynamic LINQ stuff and Property.PropertyToString() is what this question is about. /// <summary> /// This defines a framework to pass, across serialized tiers, sorting logic to be performed. /// </summary> /// <typeparam name="TModel">This is the object type that you are filtering.</typeparam> /// <typeparam name="TProperty">This is the property on the object that you are filtering.</typeparam> [Serializable] public class SortOption<TModel, TProperty> : ISerializable where TModel : class { /// <summary> /// Convenience constructor. /// </summary> /// <param name="property">The property to sort.</param> /// <param name="isAscending">Indicates if the sorting should be ascending or descending</param> /// <param name="priority">Indicates the sorting priority where 0 is a higher priority than 10.</param> public SortOption(Expression<Func<TModel, TProperty>> property, bool isAscending = true, int priority = 0) { Property = property; IsAscending = isAscending; Priority = priority; } /// <summary> /// Default Constructor. /// </summary> public SortOption() : this(null) { } /// <summary> /// This is the field on the object to filter. /// </summary> public Expression<Func<TModel, TProperty>> Property { get; set; } /// <summary> /// This indicates if the sorting should be ascending or descending. /// </summary> public bool IsAscending { get; set; } /// <summary> /// This indicates the sorting priority where 0 is a higher priority than 10. /// </summary> public int Priority { get; set; } #region Implementation of ISerializable /// <summary> /// This is the constructor called when deserializing a SortOption. /// </summary> protected SortOption(SerializationInfo info, StreamingContext context) { IsAscending = info.GetBoolean("IsAscending"); Priority = info.GetInt32("Priority"); // We just persisted this by the PropertyName. So let's rebuild the Lambda Expression from that. Property = DynamicExpression.ParseLambda<TModel, TProperty>(info.GetString("Property"), default(TModel), default(TProperty)); } /// <summary> /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param> public void GetObjectData(SerializationInfo info, StreamingContext context) { // Just stick the property name in there. We'll rebuild the expression based on that on the other end. info.AddValue("Property", Property.PropertyToString()); info.AddValue("IsAscending", IsAscending); info.AddValue("Priority", Priority); } #endregion }

    Read the article

  • Using Lambda Expressions trees with IEnumerable

    - by Loathian
    I've been trying to learn more about using Lamba expression trees and so I created a simple example. Here is the code, this works in LINQPad if pasted in as a C# program. void Main() { IEnumerable<User> list = GetUsers().Where(NameContains("a")); list.Dump("Users"); } // Methods public IEnumerable<User> GetUsers() { yield return new User{Name = "andrew"}; yield return new User{Name = "rob"}; yield return new User{Name = "chris"}; yield return new User{Name = "ryan"}; } public Expression<Func<User, bool>> NameContains(string namePart) { return u => u.Name.Contains(namePart); } // Classes public class User { public string Name { get; set; } } This results in the following error: The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. However if I just substitute the first line in main with this: IEnumerable<User> list = GetUsers().Where(u => u.Name.Contains("a")); It works fine. Can tell me what I'm doing wrong, please?

    Read the article

  • Can't pass a single parameter to lambda function in MVVM Light Toolkit's RelayCommand

    - by Dave
    I don't know if there's a difference between Josh Smith's and Laurent Bugnion's implementations of RelayCommand or not, but everywhere I've looked, it sounds like the Execute portion of RelayCommand can take 0 or 1 parameters. I've only been able to get it to work with 0. When I try something like: public class Test { public RelayCommand MyCommand { get; set; } public Test() { MyCommand = new RelayCommand((param) => SomeFunc(param)); } private void SomeFunc( object param) { } } I get the error: Delegate 'System.Action' does not take '1' arguments. Just to make sure I am not insane, I went to the definition of RelayCommand to make sure I didn't have some rogue implementation in my solution somewhere, but sure enough, it was just Action, and not Action<. What on earth am I missing here?

    Read the article

  • Precompile Lambda Expression Tree conversions as constants?

    - by Nathan
    It is fairly common to take an Expression tree, and convert it to some other form, such as a string representation (for example this question and this question, and I suspect Linq2Sql does something similar). In many cases, perhaps even most cases, the Expression tree conversion will always be the same, i.e. if I have a function public string GenerateSomeSql(Expression<Func<TResult, TProperty>> expression) then any call with the same argument will always return the same result for example: GenerateSomeSql(x => x.Age) //suppose this will always return "select Age from Person" GenerateSomeSql(x => x.Ssn) //suppose this will always return "select Ssn from Person" So, in essence, the function call with a particular argument is really just a constant, except time is wasted at runtime re-computing it continuously. Assuming, for the sake of argument, that the conversion was sufficiently complex to cause a noticeable performance hit, is there any way to pre-compile the function call into an actual constant?

    Read the article

  • javascript scope problem when lambda function refers to a variable in enclosing loop

    - by Stefan Blixt
    First question on stackoverflow :) Hope I won't embarrass myself... I have a javascript function that loads a list of albums and then it creates a list item for each album. The list item should be clickable, so I call jQuery's click() with a function that does stuff. I do this in a loop. My problem is that all items seem to get the same click function, even though I try to make a new one that does different stuff in each iteration. Another possibility is that the iteration variable is global somehow, and the function refers to it. Code below. debug() is just an encapsulation of Firebug's console.debug(). function processAlbumList(data, c) { for (var album in data) { var newAlbum = $('<li class="albumLoader">' + data[album].title + '</li>').clone(); var clickAlbum = function() { debug("contents: " + album); }; debug("Album: " + album + "/" + data[album].title); $('.albumlist').append(newAlbum); $(newAlbum).click(clickAlbum); } } Here is a transcript of what it prints when the above function runs, after that are some debug lines caused by me clicking on different items. It always prints "10", which is the last value that the album variable takes (there are 10 albums). Album: 0/Live on radio.electro-music.com Album: 1/Doodles Album: 2/Misc Stuff Album: 3/Drawer Collection Album: 4/Misc Electronic Stuff Album: 5/Odds & Ends Album: 6/Tumbler Album: 7/Bakelit 32 Album: 8/Film Album: 9/Bakelit Album: 10/Slow Zoom/Atomic Heart contents: 10 contents: 10 contents: 10 contents: 10 contents: 10 Any ideas? Driving me up the wall, this is. :) /Stefan

    Read the article

  • Linq Queries converting to lambda expressions ?

    - by Freshblood
    Hello from item in range where item % 2 ==0 select i ; is converting to lamda expressions as below range.where(item % 2 ==0).select(x=>x). I feel that first way of linq is translating next one and if it is ,so is there any optimization like this range.where(item & 2 == 0) instead of other one ?

    Read the article

  • Pattern matching for lambda expressions

    - by alphomega
    21 --Primitive recursion constructor 22 pr :: ([Int] -> Int) -> ([Int] -> Int) -> ([Int] -> Int) 23 pr f g = \xs 0 -> f xs 24 pr f g = \xs (y+1) -> g xs y ((pr f g) xs y) I want the function this function creates to act differently on different inputs, so that it can create a recursive function. As expected, the above code doesn't work. How do I do something like pattern matching, but for the function it creates? Thanks

    Read the article

  • Creating Delegates With Lambda Expressions in F#

    - by Matt H
    Why does... type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list) (d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x) not compile, when: type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list, d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x)) does? The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple. Error 1 This function takes too many arguments, or is used in a context where a function is not expected

    Read the article

  • How optimize by lambda expression

    - by simply denis
    I have a very similar function is only one previous report and the other future, how can I optimize and write beautiful? public bool AnyPreviousReportByGroup(int groupID) { if(this.GroupID == groupID) { return true; } else { return PreviousReport.AnyPreviousReportByGroup(groupID); } } public bool AnyNextReportByGroup(int groupID) { if (this.GroupID == groupID) { return true; } else { return NextReport.AnyNextReportByGroup(groupID); } }

    Read the article

  • Cannot we use break statement in a lambda(C#3.0)

    - by Newbie
    Consider this List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6 }; int j = 0; intList.ForEach(i => { if (i.Equals(1)) { j = i; break; } } ); Throwing error: No enclosing loop out of which to break or continue But the below works foreach(int i in intList) { j = i; break; } Why so. Am I making any mistake. Thanks

    Read the article

  • parallel_for_each from amp.h – part 1

    - by Daniel Moth
    This posts assumes that you've read my other C++ AMP posts on index<N> and extent<N>, as well as about the restrict modifier. It also assumes you are familiar with C++ lambdas (if not, follow my links to C++ documentation). Basic structure and parameters Now we are ready for part 1 of the description of the new overload for the concurrency::parallel_for_each function. The basic new parallel_for_each method signature returns void and accepts two parameters: a grid<N> (think of it as an alias to extent) a restrict(direct3d) lambda, whose signature is such that it returns void and accepts an index of the same rank as the grid So it looks something like this (with generous returns for more palatable formatting) assuming we are dealing with a 2-dimensional space: // some_code_A parallel_for_each( g, // g is of type grid<2> [ ](index<2> idx) restrict(direct3d) { // kernel code } ); // some_code_B The parallel_for_each will execute the body of the lambda (which must have the restrict modifier), on the GPU. We also call the lambda body the "kernel". The kernel will be executed multiple times, once per scheduled GPU thread. The only difference in each execution is the value of the index object (aka as the GPU thread ID in this context) that gets passed to your kernel code. The number of GPU threads (and the values of each index) is determined by the grid object you pass, as described next. You know that grid is simply a wrapper on extent. In this context, one way to think about it is that the extent generates a number of index objects. So for the example above, if your grid was setup by some_code_A as follows: extent<2> e(2,3); grid<2> g(e); ...then given that: e.size()==6, e[0]==2, and e[1]=3 ...the six index<2> objects it generates (and hence the values that your lambda would receive) are:    (0,0) (1,0) (0,1) (1,1) (0,2) (1,2) So what the above means is that the lambda body with the algorithm that you wrote will get executed 6 times and the index<2> object you receive each time will have one of the values just listed above (of course, each one will only appear once, the order is indeterminate, and they are likely to call your code at the same exact time). Obviously, in real GPU programming, you'd typically be scheduling thousands if not millions of threads, not just 6. If you've been following along you should be thinking: "that is all fine and makes sense, but what can I do in the kernel since I passed nothing else meaningful to it, and it is not returning any values out to me?" Passing data in and out It is a good question, and in data parallel algorithms indeed you typically want to pass some data in, perform some operation, and then typically return some results out. The way you pass data into the kernel, is by capturing variables in the lambda (again, if you are not familiar with them, follow the links about C++ lambdas), and the way you use data after the kernel is done executing is simply by using those same variables. In the example above, the lambda was written in a fairly useless way with an empty capture list: [ ](index<2> idx) restrict(direct3d), where the empty square brackets means that no variables were captured. If instead I write it like this [&](index<2> idx) restrict(direct3d), then all variables in the some_code_A region are made available to the lambda by reference, but as soon as I try to use any of those variables in the lambda, I will receive a compiler error. This has to do with one of the direct3d restrictions, where only one type can be capture by reference: objects of the new concurrency::array class that I'll introduce in the next post (suffice for now to think of it as a container of data). If I write the lambda line like this [=](index<2> idx) restrict(direct3d), all variables in the some_code_A region are made available to the lambda by value. This works for some types (e.g. an integer), but not for all, as per the restrictions for direct3d. In particular, no useful data classes work except for one new type we introduce with C++ AMP: objects of the new concurrency::array_view class, that I'll introduce in the post after next. Also note that if you capture some variable by value, you could use it as input to your algorithm, but you wouldn’t be able to observe changes to it after the parallel_for_each call (e.g. in some_code_B region since it was passed by value) – the exception to this rule is the array_view since (as we'll see in a future post) it is a wrapper for data, not a container. Finally, for completeness, you can write your lambda, e.g. like this [av, &ar](index<2> idx) restrict(direct3d) where av is a variable of type array_view and ar is a variable of type array - the point being you can be very specific about what variables you capture and how. So it looks like from a large data perspective you can only capture array and array_view objects in the lambda (that is how you pass data to your kernel) and then use the many threads that call your code (each with a unique index) to perform some operation. You can also capture some limited types by value, as input only. When the last thread completes execution of your lambda, the data in the array_view or array are ready to be used in the some_code_B region. We'll talk more about all this in future posts… (a)synchronous Please note that the parallel_for_each executes as if synchronous to the calling code, but in reality, it is asynchronous. I.e. once the parallel_for_each call is made and the kernel has been passed to the runtime, the some_code_B region continues to execute immediately by the CPU thread, while in parallel the kernel is executed by the GPU threads. However, if you try to access the (array or array_view) data that you captured in the lambda in the some_code_B region, your code will block until the results become available. Hence the correct statement: the parallel_for_each is as-if synchronous in terms of visible side-effects, but asynchronous in reality.   That's all for now, we'll revisit the parallel_for_each description, once we introduce properly array and array_view – coming next. Comments about this post by Daniel Moth welcome at the original blog.

    Read the article

  • Passing a parameter using RelayCommand defined in the ViewModel (from Josh Smith example)

    - by eesh
    I would like to pass a parameter defined in the XAML (View) of my application to the ViewModel class by using the RelayCommand. I followed Josh Smith's excellent article on MVVM and have implemented the following. XAML Code <Button Command="{Binding Path=ACommandWithAParameter}" CommandParameter="Orange" HorizontalAlignment="Left" Style="{DynamicResource SimpleButton}" VerticalAlignment="Top" Content="Button"/> ViewModel Code public RelayCommand _aCommandWithAParameter; /// <summary> /// Returns a command with a parameter /// </summary> public RelayCommand ACommandWithAParameter { get { if (_aCommandWithAParameter == null) { _aCommandWithAParameter = new RelayCommand( param => this.CommandWithAParameter("Apple") ); } return _aCommandWithAParameter; } } public void CommandWithAParameter(String aParameter) { String theParameter = aParameter; } #endregion I set a breakpoint in the CommandWithAParameter method and observed that aParameter was set to "Apple", and not "Orange". This seems obvious as the method CommandWithAParameter is being called with the literal String "Apple". However, looking up the execution stack, I can see that "Orange", the CommandParameter I set in the XAML is the parameter value for RelayCommand implemenation of the ICommand Execute interface method. That is the value of parameter in the method below of the execution stack is "Orange", public void Execute(object parameter) { _execute(parameter); } What I am trying to figure out is how to create the RelayCommand ACommandWithAParameter property such that it can call the CommandWithAParameter method with the CommandParameter "Orange" defined in the XAML. Is there a way to do this? Why do I want to do this? Part of "On The Fly Localization" In my particular implementation I want to create a SetLanguage RelayCommand that can be bound to multiple buttons. I would like to pass the two character language identifier ("en", "es", "ja", etc) as the CommandParameter and have that be defined for each "set language" button defined in the XAML. I want to avoid having to create a SetLanguageToXXX command for each language supporting and hard coding the two character language identifier into each RelayCommand in the ViewModel.

    Read the article

  • C# Func delegate with params type

    - by Sarah Vessels
    How, in C#, do I have a Func parameter representing a method with this signature? XmlNode createSection(XmlDocument doc, params XmlNode[] childNodes) I tried having a parameter of type Func<XmlDocument, params XmlNode[], XmlNode> but, ooh, ReSharper/Visual Studio 2008 go crazy highlighting that in red.

    Read the article

  • Why model => model.Reason_ID turns to model =>Convert(model.Reason_ID)

    - by er-v
    I have my own html helper extension, wich I use this way <%=Html.LocalizableLabelFor(model => model.Reason_ID, Register.PurchaseReason) %> which declared like this. public static MvcHtmlString LocalizableLabelFor<T>(this HtmlHelper<T> helper, Expression<Func<T, object>> expr, string captionValue) where T : class { return helper.LocalizableLabelFor(ExpressionHelper.GetExpressionText(expr), captionValue); } but when I open it in debugger expr.Body.ToString() will show me Convert(model.Reason_ID). But should model.Reason_ID. That's a big problem, becouse ExpressionHelper.GetExpressionText(expr) returns empty string. What a strange magic is that? How can I get rid of it?

    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

  • Ambiguous call between methods ASP.NET MVC

    - by GuiPereira
    I'm pretty new in ASP.NET MVC (about 3 months) and i've the followin issue: I have a Entity Class called 'Usuario' in a ClassLibrary referenced as 'Core' and, when i create a strongly-typed view and add a html.textboxfor< like: <%= Html.TextBoxFor(u => u.Login) %> it raises the following error: Error 3 The call is ambiguous between the following methods or properties: 'Microsoft.Web.Mvc.ExpressionInputExtensions.TextBoxFor<Core.Usuario,string>(System.Web.Mvc .HtmlHelper<Core.Usuario>, System.Linq.Expressions.Expression<System.Func<Core.Usuario,string>>)' and 'System.Web.Mvc.Html.InputExtensions.TextBoxFor<Core.Usuario,string>(System.Web.Mvc.HtmlHel per<Core.Usuario>, System.Linq.Expressions.Expression<System.Func<Core.Usuario,string>>)' d:\Documents\Visual Studio 2008\Projects\GuiPereiraMVC2\GuiPereiraMVC2\Views\Gestao\Index.aspx 20 25 GuiPereiraMVC2 anyone knows why?

    Read the article

  • Using antlr and the DLR together -- AST conversion

    - by RCIX
    I have an AST generated via ANTLR, and I need to convert it to a DLR-compatible one (Expression Trees). However, it would seem that i can't use tree pattern matchers for this as expression trees need their subtrees at instantiation (which i can't get). What solution would be best for me to use?

    Read the article

  • Call asp.net mvc Html Helper within custom html helper with expression parameter

    - by Frank Michael Kraft
    I am trying to write an html helper extension within the asp.net mvc framework. public static MvcHtmlString PlatformNumericTextBoxFor<TModel>(this HtmlHelper instance, TModel model, Expression<Func<TModel,double>> selector) where TModel : TableServiceEntity { var viewModel = new PlatformNumericTextBox(); var func = selector.Compile(); MemberExpression memExpession = (MemberExpression)selector.Body; string name = memExpession.Member.Name; var message = instance.ValidationMessageFor<TModel, double>(selector); viewModel.name = name; viewModel.value = func(model); viewModel.validationMessage = String.Empty; var result = instance.Partial(typeof(PlatformNumericTextBox).Name, viewModel); return result; } The line var message = instance.ValidationMessageFor<TModel, double>(selector); has a syntax error. But I do not understand it. The error is: Fehler 2 "System.Web.Mvc.HtmlHelper" enthält keine Definition für "ValidationMessageFor", und die Überladung der optimalen Erweiterungsmethode "System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression)" weist einige ungültige Argumente auf. C:\Projects\WorkstreamPlatform\WorkstreamPlatform_WebRole\Extensions\PlatformHtmlHelpersExtensions.cs 97 27 WorkstreamPlatform_WebRole So according to the message, the parameter is invalid. But the method is actually declared like this: public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression); So actually it should work.

    Read the article

  • C# - closures over class fields inside an initializer?

    - by Richard Berg
    Consider the following code: using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var square = new Square(4); Console.WriteLine(square.Calculate()); } } class MathOp { protected MathOp(Func<int> calc) { _calc = calc; } public int Calculate() { return _calc(); } private Func<int> _calc; } class Square : MathOp { public Square(int operand) : base(() => _operand * _operand) // runtime exception { _operand = operand; } private int _operand; } } (ignore the class design; I'm not actually writing a calculator! this code merely represents a minimal repro for a much bigger problem that took awhile to narrow down) I would expect it to either: print "16", OR throw a compile time error if closing over a member field is not allowed in this scenario Instead I get a nonsensical exception thrown at the indicated line. On the 3.0 CLR it's a NullReferenceException; on the Silverlight CLR it's the infamous Operation could destabilize the runtime.

    Read the article

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