Search Results

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

Page 5/99 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • LINQ query and lambda expressions

    - by user329269
    I'm trying to write a LINQ query and am having problems. I'm not sure if lambda expressions are the answer or not but I think they may be. I have two combo boxes on my form: "State" and "Color". I want to select Widgets from my database based on the values of these two dropdowns. My widgets can be in one of the following states: Not Started, In Production, In Finishing, In Inventory, Sold. Widgets can have any color in the 'color' table in the database. The 'state' combobox has selections "Not Sold," "In Production/Finishing", "Not Started," "In Production," "In Finishing," "In Inventory," "Sold." (I hope these are self-explanatory.) The 'color' dropdown has "All Colors," and a separate item for each color in the database. How can I create a LINQ query to select the widgets I want from the database based on the dropdowns?

    Read the article

  • Linq and Lamba Expressions - while walking a selected list perform an action

    - by Prescott
    Hey, I'm very new to linq and lamba expressions. I'm trying to walk a collection, and when I find an item that meets some criteria I'd like to add that to another separate collection. My linq to walk the collection looks like this (this works fine): From i as MyCustomItem In MyCustomItemCollection Where i.Type = "SomeType" Select i I need each of the select items to then be added to a ListItemCollection, I know I can assign that linq query to a variable, and then do a for each loop adding a new ListItem to the collection, but I'm trying o find a way to add each item to the new ListItemcollection while walking, not a second loop. Thanks ~P

    Read the article

  • Problem with nested lambda expressions.

    - by Lehto
    Hey I'm trying to do a nested lambda expression like to following: textLocalizationTable.Where( z => z.SpokenLanguage.Any( x => x.FromCulture == "en-GB") ).ToList(); but i get the error: Member access 'System.String FromCulture' of 'DomainModel.Entities.SpokenLanguage' not legal on type 'System.Data.Linq.EntitySet`1[DomainModel.Entities.SpokenLanguage]. TextLocalization has this relation to spokenlanguage: [Association(OtherKey = "LocalizationID", ThisKey = "LocalizationID", Storage = "_SpokenLanguage")] private EntitySet<SpokenLanguage> _SpokenLanguage = new EntitySet<SpokenLanguage>(); public EntitySet<SpokenLanguage> SpokenLanguage { set { _SpokenLanguage = value; } get { return _SpokenLanguage; } } Any idea what is wrong?

    Read the article

  • .NET C# setting the value of a field defined by a lambda selector

    - by Frank Michael Kraft
    I have a generic class HierarchicalBusinessObject. In the constructor of the class I pass a lambda expression that defines a selector to a field of TModel. protected HierarchicalBusinessObject (Expression<Func<TModel,string>> parentSelector) A call would look like this, for example: public class WorkitemBusinessObject : HierarchicalBusinessObject<Workitem,WorkitemDataContext> { public WorkitemBusinessObject() : base(w => w.SuperWorkitem, w => w.TopLevel == true) { } } I am able to use the selector for read within the class. For example: sourceList.Select(_parentSelector.Compile()).Where(... Now I am asking myself how I could use the selector to set a value to the field. Something like selector.Body() .... Field...

    Read the article

  • Lambda expressions and nullable types

    - by Mathew
    I have two samples of code. One works and returns the correct result, one throws a null reference exception. What's the difference? I know there's some magic happening with capturing variables for the lambda expression but I don't understand what's going on behind the scenes here. int? x = null; bool isXNull = !x.HasValue; // this works var result = from p in data.Program where (isXNull) select p; return result.Tolist(); // this doesn't var result2 = from p in data.Program where (!x.HasValue) select p; return result2.ToList();

    Read the article

  • Using a linq or lambda expression in C# return a collection plus a single value

    - by ahsteele
    I'd like to return a collection plus a single value. Presently I am using a field to create a new list adding a value to the list and then returning the result. Is there a way to do this with a linq or lambda expression? private List<ChargeDetail> _chargeBreakdown = new List<ChargeDetail>(); public ChargeDetail PrimaryChargeDetail { get; set; } public List<ChargeDetail> ChargeBreakdown { get { List<ChargeDetail> result = new List<ChargeDetail>(_chargeBreakdown); result.Add(PrimaryChargeDetail); return result; } }

    Read the article

  • Using Lambda Statements for Event Handlers

    - by lush
    I currently have a page which is declared as follows: public partial class MyPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //snip MyButton.Click += (o, i) => { //snip } } } I've only recently moved to .NET 3.5 from 1.1, so I'm used to writing event handlers outside of the Page_Load. My question is; are there any performance drawbacks or pitfalls I should watch out for when using the lambda method for this? I prefer it, as it's certainly more concise, but I do not want to sacrifice performance to use it. Thanks.

    Read the article

  • Wrap Sub as Function for use in Lambda

    - by Luhmann
    I have a problem with VB and Moq. I need to call a verify on a Sub. Like so: logger.Verify(Function(x) x.Log, Times.AtLeastOnce) And my logger looks like this: Public Interface ILogger Sub Log() End Interface But with VB this is not possible, because the Log method is a Sub, and thereby does not produce a value. I don't want to change the method to be a function. Whats the cleanest way of working around this limitation and is there any way to wrap the Sub as a Function like the below? logger.Verify(Function(x) ToFunc(AddressOf x.Log)) I have tried this, but i get: Lambda Parameter not in scope

    Read the article

  • lambda+for_each+delete on STL containers

    - by rubenvb
    I'm trying to get a simple delete every pointer in my vector/list/... function written with an ultra cool lambda function. Mind you, I don't know c**p about those things :) template <typename T> void delete_clear(T const& cont) { for_each(T.begin(), T.end(), [](???){ ???->delete() } ); T.clear(); } I have no clue what to fill in for the ???'s. Any help is greatly appreciated!

    Read the article

  • Using linq to combine objects

    - by DotnetDude
    I have 2 instances of a class that implements the IEnumerable interface. I would like to create a new object and combine both of them into one. I understand I can use the for..each to do this. Is there a linq/lambda expression way of doing this?

    Read the article

  • Entity Framework - Condition on one to many join (Lambda)

    - by nirpi
    Hi, I have 2 entities: Customer & Account, where a customer can have multiple accounts. On the account, I have a "PlatformTypeId" field, which I need to condition on (multiple values), among other criterions. I'm using Lambda expressions, to build the query. Here's a snippet: var customerQuery = (from c in context.CustomerSet.Include("Accounts") select c); if (criterions.UserTypes != null && criterions.UserTypes.Count() > 0) { List<short> searchCriterionsUserTypes = criterions.UserTypes.Select(i => (short)i).ToList(); customerQuery = customerQuery.Where(CommonDataObjects.LinqTools.BuildContainsExpression<Customer, short>(c => c.UserTypeId, searchCriterionsUserTypes)); } // Other criterions, including the problematic platforms condition (below) var customers = customerQuery.ToList(); I can't figure out how to build the accounts' platforms condition: if (criterions.Platforms != null && criterions.Platforms.Count() > 0) { List<short> searchCriterionsPlatforms = criterions.Platforms.Select(i => (short)i).ToList(); customerQuery = customerQuery.Where(c => c.Accounts.Where(LinqTools.BuildContainsExpression<Account, short>(a => a.PlatformTypeId, searchCriterionsPlatforms))); } (The BuildContainsExpression is a method we use to build the expression for the multi-select) I'm getting a compilation 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. Any idea how to fix this? Thanks, Nir.

    Read the article

  • Convert Lambda from C# to VB.NET

    - by Iosu
    How would I translate this C# lambda expression into VB.NET ? query.ExecuteAsync(op => op.Results.ForEach(Employees.Add)); using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; using IdeaBlade.Core; using IdeaBlade.EntityModel; namespace SimpleSteps { public class MainPageViewModel { public MainPageViewModel() { Employees = new ObservableCollection(); var mgr = new NorthwindIBEntities(); var query = mgr.Employees; query.ExecuteAsync(op = op.Results.ForEach(Employees.Add)); } public ObservableCollection<Employee> Employees { get; private set; } } }

    Read the article

  • linq-to-sql combine child expressions

    - by VictorS
    I need to create and combine several expressions for child entity into one to use it on "Any" operator of a parent. Code now looks like this: Expresion<Child, bool> startDateExpression = t => t.start_date >= startDate; Expression<Child, bool> endDateExpression = t => t.end_date <= endDate; .... ParameterExpression param = startDateExpression.Parameters[0]; Expression<Func<T, bool>> Combined = Expression.Lambda<Func<Child, bool>>( Expression.AndAlso(startDateExpression.Body, startDateExpression.Body), param); //but now I am trying to use combined expression on parent //this line fails just to give an idea on what I am trying to do: //filter type is IQueryable<Parent>; var filter = filter.Where(p =>p.Children.Any(Combined)); How can I do that? Is there better(more elegant way way of doing it?

    Read the article

  • Help me clean up this crazy lambda with the out keyword

    - by Sarah Vessels
    My code looks ugly, and I know there's got to be a better way of doing what I'm doing: private delegate string doStuff( PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt ); private bool tryEncryptPassword( doStuff encryptPassword, out string errorMessage ) { ...get some variables... string encryptedPassword = encryptPassword(encrypter, publicKey, privateKey, out salt); ... } This stuff so far doesn't bother me. It's how I'm calling tryEncryptPassword that looks so ugly, and has duplication because I call it from two methods: public bool method1(out string errorMessage) { string rawPassword = "foo"; return tryEncryptPassword( (PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt) => encrypter.EncryptPasswordAndDoStuff( // Overload 1 rawPassword, publicKey, privateKey, out salt ), out errorMessage ); } public bool method2(SecureString unencryptedPassword, out string errorMessage) { return tryEncryptPassword( (PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt) => encrypter.EncryptPasswordAndDoStuff( // Overload 2 unencryptedPassword, publicKey, privateKey, out salt ), out errorMessage ); } Two parts to the ugliness: I have to explicitly list all the parameter types in the lambda expression because of the single out parameter. The two overloads of EncryptPasswordAndDoStuff take all the same parameters except for the first parameter, which can either be a string or a SecureString. So method1 and method2 are pretty much identical, they just call different overloads of EncryptPasswordAndDoStuff. Any suggestions? Edit: if I apply Jeff's suggestions, I do the following call in method1: return tryEncryptPassword( (encrypter, publicKey, privateKey) => { var result = new EncryptionResult(); string salt; result.EncryptedValue = encrypter.EncryptPasswordAndDoStuff( rawPassword, publicKey, privateKey, out salt ); result.Salt = salt; return result; }, out errorMessage ); Much the same call is made in method2, just with a different first value to EncryptPasswordAndDoStuff. This is an improvement, but it still seems like a lot of duplicated code.

    Read the article

  • Using lambda expressions and linq

    - by Andy
    So I've just started working with linq as well as using lambda expressions. I've run into a small hiccup while trying to get some data that I want. This method should return a list of all projects that are open or in progress from Jira Here's the code public static List<string> getOpenIssuesListByProject(string _projectName) { JiraSoapServiceService jiraSoapService = new JiraSoapServiceService(); string token = jiraSoapService.login(DEFAULT_UN, DEFAULT_PW); string[] keys = { getProjectKey(_projectName) }; RemoteStatus[] statuses = jiraSoapService.getStatuses(token); var desiredStatuses = statuses.Where(x => x.name == "Open" || x.name == "In Progress") .Select(x=>x.id); RemoteIssue[] AllIssues = jiraSoapService.getIssuesFromTextSearchWithProject(token, keys, "", 99); IEnumerable<RemoteIssue> openIssues = AllIssues.Where(x=> { foreach (var v in desiredStatuses) { if (x.status == v) return true; else return false; } return false; }); return openIssues.Select(x => x.key).ToList(); } Right now this only select issues that are "Open", and seems to skip those that are "In Progress". My question: First, why am I only getting the "Open" Issues, and second is there a better way to do this? The reason I get all the statuses first is that the issue only stores that statuses ID, so I get all the statuses, get the ID's that match "Open" and "In Progress", and then match those ID numbers to the issues status field.

    Read the article

  • Create lambda action from function expression

    - by Martin Robins
    It is relatively easy to create a lambda function that will return the value of a property from an object, even including deep properties... Func<Category, string> getCategoryName = new Func<Category, string>(c => c.Name); and this can be called as follows... string categoryName = getCategoryName(this.category); But, given only the resulting function above (or the expression originally used to create the function), can anybody provide an easy way to create the opposing action... Action<Category, string> setCategoryName = new Action<Category, string>((c, s) => c.Name = s); ...that will enable the same property value to be set as follows? setCategoryName(this.category, ""); Note that I am looking for a way to create the action programatically from the function or expression - I hope that I have shown that I already know how to create it manually. I am open to answers that work in both .net 3.5 and 4.0. Thanks.

    Read the article

  • for loop vs std::for_each with lambda

    - by Andrey
    Let's consider a template function written in C++11 which iterates over a container. Please exclude from consideration the range loop syntax because it is not yet supported by the compiler I'm working with. template <typename Container> void DoSomething(const Container& i_container) { // Option #1 for (auto it = std::begin(i_container); it != std::end(i_container); ++it) { // do something with *it } // Option #2 std::for_each(std::begin(i_container), std::end(i_container), [] (typename Container::const_reference element) { // do something with element }); } What are pros/cons of for loop vs std::for_each in terms of: a) performance? (I don't expect any difference) b) readability and maintainability? Here I see many disadvantages of for_each. It wouldn't accept a c-style array while the loop would. The declaration of the lambda formal parameter is so verbose, not possible to use auto there. It is not possible to break out of for_each. In pre- C++11 days arguments against for were a need of specifying the type for the iterator (doesn't hold any more) and an easy possibility of mistyping the loop condition (I've never done such mistake in 10 years). As a conclusion, my thoughts about for_each contradict the common opinion. What am I missing here?

    Read the article

  • Can I use a method as a lambda?

    - by NewAlexandria
    I have an interface the defines a group of conditions. it is one of several such interfaces that will live with other models. These conditions will be called by a message queue handler to determine completeness of an alert. All the alert calls will be the same, and so I seek to DRY up the enqueue calls a bit, by abstracting the the conditions into their own methods (i question if methods is the right technique). I think that by doing this I will be able to test each of these conditions. class Loan module AlertTriggers def self.included(base) base.extend LifecycleScopeEnqueues # this isn't right Loan::AlertTriggers::LifecycleScopeEnqueues.instance_method.each do |cond| class << self def self.cond ::AlertHandler.enqueue_alerts( {:trigger => Loan.new}, cond ) end end end end end module LifecycleScopeEnqueues def student_awaiting_cosigner lambda { |interval, send_limit, excluding| excluding ||= '' Loan.awaiting_cosigner. where('loans.id not in (?)', excluding.map(&:id) ). joins(:petitions). where('petitions.updated_at > ?', interval.days.ago). where('petitions.updated_at <= ?', send_limit.days.ago) } end end I've considered alternatives, where each of these methods act like a scope. Down that road, I'm not sure how to have AlertHandler be the source of interval, send_limit, and excluding, which it passes to the block/proc when calling it.

    Read the article

  • Javascript to match a specific number using regular expressions

    - by ren33
    I was using javascript to detect for specific key strokes and while writing the method I thought I'd try regular expressions and the test() method and came up with: if (/8|9|37|38|46|47|48|49|50|51|52|53|54|55|56|57|96|97|98|99|100|101|102|103|104|105|110/.test(num)) { // do something if there's a match } This doesn't seem to work 100% as some values seem to make it past the regex test, such as 83. I've since moved on, but I'm still curious as to why this didn't work.

    Read the article

  • PHP and Regular Expressions question?

    - by php
    I was wondering if the codes below are the correct way to check for a street address, email address, password, city and url using preg_match using regular expressions? And if not how should I fix the preg_match code? preg_match ('/^[A-Z0-9 \'.-]{1,255}$/i', $trimmed['address']) //street address preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $trimmed['email'] //email address preg_match ('/^\w{4,20}$/', $trimmed['password']) //password preg_match ('/^[A-Z \'.-]{1,255}$/i', $trimmed['city']) //city preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $trimmed['url']) //url

    Read the article

  • BASH Arithmetic Expressions

    - by Arko
    I had used several ways to do some simple integer arithmetic in BASH (3.2). But I can't figure out the best (preferred) way to do it. result=`expr 1 + 2` result=$(( 1 + 2 )) let "result = 1 + 2" What are the fundamental differences between those expressions? Is there other ways to do the same? Is the use of a tool like bc mandatory for floating point arithmetic? result=`echo "7/354" | bc`

    Read the article

  • c# Lambda Expression built with LinqKit does not compile

    - by Frank Michael Kraft
    This lambda does not compile, but I do not understand why. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using LinqKit; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var barModel = new BarModel(); string id = "some"; Console.WriteLine(barModel.subFor(id).ToString()); // output: m => (True AndAlso (m.key == value(ConsoleApplication2.Bar`1+<>c__DisplayClass0[ConsoleApplication2.Model]).id)) Console.ReadKey(); var subworkitems = barModel.list.Where(barModel.subFor(id).Compile()); // Exception {"variable 'm' of type 'ConsoleApplication2.Model' referenced from scope '', but it is not defined"} Console.WriteLine(subworkitems.ToString()); Console.ReadKey(); } } class Bar<TModel> { public Bar(Expression<Func<TModel, string>> foreignKeyExpression) { _foreignKeyExpression = foreignKeyExpression; } private Expression<Func<TModel, string>> _foreignKeyExpression { get; set; } public Expression<Func<TModel, bool>> subFor(string id) { var ex = forTargetId(id); return ex; } public Expression<Func<TModel, bool>> forTargetId(String id) { var fc = _foreignKeyExpression; Expression<Func<TModel, bool>> predicate = m => true; var result = predicate.And(m => fc.Invoke(m) == id).Expand(); return result; } } class Model { public string key; public string value; } class BarModel : Bar<Model> { public List<Model> list; public BarModel() : base(m => m.key) { list = new List<Model>(); } } }

    Read the article

  • Formal Languages, Inductive Proofs &amp; Regular Expressions

    - by MarkPearl
    So I am slogging away at my UNISA stuff. I have just finished doing the initial once non stop read through the first 11 chapters of my COS 201 Textbook - “Introduction to Computer Theory 2nd Edition” by Daniel Cohen. It has been an interesting couple of days, with familiar concepts coming up as well as some new territory. In this posting I am going to cover the first couple of chapters of the book. Let start with Formal Languages… What exactly is a formal language? Pretty much a no duh question for me but still a good one to ask – a formal language is a language that is defined in a precise mathematical way. Does that mean that the English language is a formal language? I would say no – and my main motivation for this is that one can have an English sentence that is correct grammatically that is also ambiguous. For example the ambiguous sentence: "I once shot an elephant in my pyjamas.” For this and possibly many other reasons that I am unaware of, English is termed a “Natural Language”. So why the importance of formal languages in computer science? Again a no duh question in my mind… If we want computers to be effective and useful tools then we need them to be able to evaluate a series of commands in some form of language that when interpreted by the device no confusion will exist as to what we were requesting. Imagine the mayhem that would exist if a computer misinterpreted a command to print a document and instead decided to delete it. So what is a Formal Language made up of… For my study purposes a language is made up of a finite alphabet. For a formal language to exist there needs to be a specification on the language that will describe whether a string of characters has membership in the language or not. There are two basic ways to do this: By a “machine” that will recognize strings of the language (e.g. Finite Automata). By a rule that describes how strings of a language can be formed (e.g. Regular Expressions). When we use the phrase “string of characters”, we can also be referring to a “word”. What is an Inductive Proof? So I am not to far into my textbook and of course it starts referring to proofs and different types. I have had to go through several different approaches of proofs in the past, but I can never remember their formal names , so when I saw “inductive proof” I thought to myself – what the heck is that? Google to the rescue… An inductive proof is like a normal proof but it employs a neat trick which allows you to prove a statement about an arbitrary number n by first proving it is true when n is 1 and then assuming it is true for n=k and showing it is true for n=k+1. The idea is that if you want to show that someone can climb to the nth floor of a fire escape, you need only show that you can climb the ladder up to the fire escape (n=1) and then show that you know how to climb the stairs from any level of the fire escape (n=k) to the next level (n=k+1). Does this sound like a form of recursion? No surprise then that in the same chapter they deal with recursive definitions. An example of a recursive definition for the language EVEN would the 3 rules below: 2 is in EVEN If x is in EVEN then so is x+2 The only elements in the set EVEN are those that be produced by the rules above. Nothing to exciting… So if a definition for a language is done recursively, then it makes sense that the language can be proved using induction. Regular Expressions So I am wondering to myself what use is this all – in fact – I find this the biggest challenge to any university material is that it is quite hard to find the immediate practical applications of some theory in real life stuff. How great was my joy when I suddenly saw the word regular expression being introduced. I had been introduced to regular expressions on Stack Overflow where I was trying to recognize if some text measurement put in by a user was in a valid form or not. For instance, the imperial system of measurement where you have feet and inches can be represented in so many different ways. I had eventually turned to regular expressions as an easy way to check if my parser could correctly parse the text or not and convert it to a normalize measurement. So some rules about languages and regular expressions… Any finite language can be represented by at least one if not more regular expressions A regular expressions is almost a rule syntax for expressing how regular languages can be formed regular expressions are cool For a regular expression to be valid for a language it must be able to generate all the words in the language and no other words. This is important. It doesn’t help me if my regular expression parses 100% of my measurement texts but also lets one or two invalid texts to pass as well. Okay, so this posting jumps around a bit – but introduces some very basic fundamentals for the subject which will be built on in later postings… Time to go and do some practical examples now…

    Read the article

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