Search Results

Search found 2819 results on 113 pages for 'conditional expressions'.

Page 31/113 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Dynamic expression tree how to

    - by Savvas Sopiadis
    Hello everybody! Implemented a generic repository with several Methods. One of those is this: public IEnumerable<T> Find(Expression<Func<T, bool>> where) { return _objectSet.Where(where); } Given to be it is easy to call this like this: Expression<Func<Culture, bool>> whereClause = c => c.CultureId > 4 ; return cultureRepository.Find(whereClause).AsQueryable(); But now i see (realize) that this kind of quering is "limiting only to one criteria". What i would like to do is this: in the above example c is of type Culture. Culture has several properties like CultureId, Name, Displayname,... How would i express the following: CultureId 4 and Name.contains('de') and in another execution Name.contains('us') and Displayname.contains('ca') and .... Those queries should be created dynamically. I had a look in Expression trees (as i thought this to be a solution to my problem - btw i never used them before) but i cannot find anything which points to my requirement. How can this be costructed? Thanks in advance

    Read the article

  • How do I tell if an action is a lambda expression?

    - by Keith
    I am using the EventAgregator pattern to subscribe and publish events. If a user subscribes to the event using a lambda expression, they must use a strong reference, not a weak reference, otherwise the expression can be garbage collected before the publish will execute. I wanted to add a simple check in the DelegateReference so that if a programmer passes in a lambda expression and is using a weak reference, that I throw an argument exception. This is to help "police" the code. Example: eventAggregator.GetEvent<RuleScheduler.JobExecutedEvent>().Subscribe ( e => resetEvent.Set(), ThreadOption.PublisherThread, false, // filter event, only interested in the job that this object started e => e.Value1.JobDetail.Name == jobName ); public DelegateReference(Delegate @delegate, bool keepReferenceAlive) { if (@delegate == null) throw new ArgumentNullException("delegate"); if (keepReferenceAlive) { this._delegate = @delegate; } else { //TODO: throw exception if target is a lambda expression _weakReference = new WeakReference(@delegate.Target); _method = @delegate.Method; _delegateType = @delegate.GetType(); } } any ideas? I thought I could check for @delegate.Method.IsStatic but I don't believe that works... (is every lambda expression a static?)

    Read the article

  • Ruby Design Problem for SQL Bulk Inserter

    - by crunchyt
    This is a Ruby design problem. How can I make a reusable flat file parser that can perform different data scrubbing operations per call, return the emitted results from each scrubbing operation to the caller and perform bulk SQL insertions? Now, before anyone gets narky/concerned, I have written this code already in a very unDRY fashion. Which is why I am asking any Ruby rockstars our there for some assitance. Basically, everytime I want to perform this logic, I create two nested loops, with custom processing in between, buffer each processed line to an array, and output to the DB as a bulk insert when the buffer size limit is reached. Although I have written lots of helpers, the main pattern is being copy pasted everytime. Not very DRY! Here is a Ruby/Pseudo code example of what I am repeating. lines_from_file.each do |line| line.match(/some regex/).each do |sub_str| # Process substring into useful format # EG1: Simple gsub() call # EG2: Custom function call to do complex scrubbing # and matching, emitting results to array # EG3: Loop to match opening/closing/nested brackets # or other delimiters and emit results to array end # Add processed lines to a buffer as SQL insert statement @buffer << PREPARED INSERT STATEMENT # Flush buffer when "buffer size limit reached" or "end of file" if sql_buffer_full || last_line_reached @dbc.insert(SQL INSERTS FROM BUFFER) @buffer = nil end end I am familiar with Proc/Lambda functions. However, because I want to pass two separate procs to the one function, I am not sure how to proceed. I have some idea about how to solve this, but I would really like to see what the real Rubyists suggest? Over to you. Thanks in advance :D

    Read the article

  • How can i filter a list of objects using lamda expression?

    - by Colour Blend
    I know i shouldn't have id's with the same value. This is just fictitious, so overlook that. I have: List<Car> carList = new List<Car>(); carList.Add(new Car() { id = 1, name = "Honda" }); carList.Add(new Car() { id = 2, name = "Toyota" }); carList.Add(new Car() { id = 1, name = "Nissan" }); I want to use Lamda Expression to retreive all cars that have an id of 1. Anticipated Result: -- Id: 1, Name: Honda -- Id: 1, Name: Nissan The problem is more filtering an object list based on a foriegn key. Please help me.

    Read the article

  • Remove duplicate characters using a regular expression

    - by Alex
    I need to Match the second and subsequent occurances of the * character using a regular expression. I'm actually using the Replace method to remove them so here's some examples of before and after: test* -> test* (no change) *test* -> *test test** *e -> test* e Is it possible to do this with a regular expression? Thanks

    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

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

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

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

    Read the article

  • How can I use linq to build an object from 1 row of data?

    - by Hcabnettek
    Hi All, I have a quick linq question. I have a stored proc that should return one row of data. I would like to use a lambda to build an object. Here's what I'm currently doing which works, but I know I should be able to use First instead of Select except I can't seem to get the syntax correct. Can anyone straighten me out here? Thanks for any help. var location = new GeoLocationDC(); DataSet ds = db.ExecuteDataSet(dbCommand); if(ds.Tables[0].Rows.Count == 1) { var rows = ds.Tables[0].AsEnumerable(); var x = rows.Select( c => new GeoLocationDC { Latitude = Convert.ToInt32(c.Field<string>("LATITUDE")), Longitude = Convert.ToInt32(c.Field<string>("LONGITUDE")) }).ToList(); if(x.Count > 0 ) { location = x[0]; } Cheers, ~ck }

    Read the article

  • lambda expression for a query on two tables that returns records from one table

    - by peetee
    I have two tables TableA (articles) int id int Type string name and TableB (compatibles) int linked_ID int tableA_ID TableA records: id=1, Type=0, name="ArticleA" id=2, Type=1, name="ArticleB" id=3, Type=2, name="ArticleC" id=4, Type=1, name="ArticleD" TableB records: linked_ID= 1, tableA_ID=2 linked_ID= 1, tableA_ID=3 linked_ID= 1, tableA_ID=4 TableB has a list of arcicels that are compatible to a certain article. I am quite new to queries (didn't need them in my projects yet). But as C# and WPF allow some pretty cool automation with Binding I would like to add a binding that returns the following: Give me all articles that are of Type 1 and compatible to my selected article (id=1). The simple part of it works well (articles has a list of all articles): private ObservableCollection<Article> _articles = new ObservableCollection<Article>(); [fill it with the available articles] and then: comboBoxArticles.ItemsSource = _articles.AsBindable().Where( c => c.Typ == 0 ); How can I extend the Where clause to query another table? Thanks a lot in advance.

    Read the article

  • How to get XML into a Dictionary with an Expression?

    - by DaveDev
    I have the following XML: <PerformancePanel page="PerformancePanel.ascx" title=""> <FundGroup heading="Net Life Managed Funds"> <fund id="17" countryid="N0" index="24103723" /> <fund id="81" countryid="N0" index="24103723" /> <fund id="127" countryid="N0" index="24103722" /> <fund id="345" countryid="N0" index="24103723" /> <fund id="346" countryid="N0" index="24103723" /> </FundGroup> <FundGroup heading="Net Life Specialist Funds"> <fund id="110" countryid="N0" index="24103717" /> <fund id="150" countryid="N0" index="24103719" /> <fund id="119" countryid="N0" index="24103720" /> <fund id="115" countryid="N0" index="24103727" /> <fund id="141" countryid="N0" index="24103711" /> <fund id="137" countryid="N0" /> <fund id="146" countryid="N0" /> <fund id="133" countryid="N0" /> <fund id="90" countryid="N0" /> <fund id="104" countryid="N0" /> <fund id="96" countryid="N0" /> </FundGroup> </PerformancePanel> I can get the data into an anonymous object as follows: var offlineFactsheet = new { PerformancePanels = (from panel in doc.Elements("PerformancePanel") select new PerformancePanel { PerformanceFunds = (from fg in panel.Elements("FundGroup") select new { Heading = (fg.Attribute("heading") == null) ? "" : (string)fg.Attribute("heading"), Funds = (from fund in fg.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList() }).ToDictionary(xx => xx.Heading, xx => xx.Funds)}; I'm trying to change my code such that I can assign the dictionary directly to a property of the class I'm working in, as described in this question. I'd like to have a Dictionary() where each header text is the key to the list of funds under it. I'm having difficulty applying the example in the linked question because that only returns a string, and this needs to return the dictionary. This is the point that I got to before it occurred to me that I'm lost!!!: this.PerformancePanels = doc.Elements("PerformancePanel").Select(e => { var control = (PerformancePanel)LoadControl(this.OfflineFactsheetPath + (string)e.Attribute("page")); control.PerformanceFunds = e.Elements("FundGroup").Select(f => { List<Fund> funds = (from fund in e.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList(); string heading = (e.Attribute("heading") == null) ? "" : (string)e.Attribute("heading"); }).ToDictionary(xx => heading, xx => Funds); return control; }).ToList(); Could someone point me in the right direction please? I'm not even sure if 'Expression' is the right terminology. Could someone fill me in on that too? Thanks.

    Read the article

  • Examining a lambda expression at runtime in C#

    - by Ben Aston
    I have a method Get on a type MyType1 accepting a Func<MyType2, bool> as a parameter. An example of its use: mytype1Instance.Get(x => x.Guid == guid)); I would like create a stub implementation of the method Get that examines the incoming lambda expression and determines what the value of guid is. Clearly the lambda could be "anything", but I'm happy for the stub to make an assumption about the lambda, that it is trying to match on the Guid property. How can I do this? I suspect it involves the use of the built-in Expression type?

    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

  • Strange LINQ to SQL Behavior

    - by mcass20
    What is wrong with the last query? Is it a bug or am I missing something? This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>David</value>%")); This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%David%</value>%")); This query returns 0 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>av</value>%")); This query returns 2 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%av%</value>%")); This query returns 0 records (correct): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>v</value>%")); This query returns 15 records (incorrect, should return 2): query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%<key>Name</key><value>%v%</value>%"));

    Read the article

  • Linq - reuse expression on child property

    - by user175528
    Not sure if what I am trying is possible or not, but I'd like to reuse a linq expression on an objects parent property. With the given classes: class Parent { int Id { get; set; } IList<Child> Children { get; set; } string Name { get; set; } } class Child{ int Id { get; set; } Parent Dad { get; set; } string Name { get; set; } } If i then have a helper Expression<Func<Parent,bool> ParentQuery() { Expression<Func<Parent,bool> q = p => p.Name=="foo"; } I then want to use this when querying data out for a child, along the lines of: using(var context=new Entities.Context) { var data=context.Child.Where(c => c.Name=="bar" && c.Dad.Where(ParentQuery)); } I know I can do that on child collections: using(var context=new Entities.Context) { var data=context.Parent.Where(p => p.Name=="foo" && p.Childen.Where(childQuery)); } but cant see any way to do this on a property that isnt a collection. This is just a simplified example, actually the ParentQuery will be more complex and I want to avoid having this repeated in multiple places as rather than just having 2 layers I'll have closer to 5 or 6, but all of them will need to reference the parent query to ensure security.

    Read the article

  • How to pass data to a C++0x lambda function that will run in a different thread?

    - by Dimitri C.
    In our company we've written a library function to call a function asynchronously in a separate thread. It works using a combination of inheritance and template magic. The client code looks as follows: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, &DemoThread::SomeFunction, stringToPassByValue); Since the introduction of lambda functions I'd like to use it in combination with lambda functions. I'd like to write the following client code: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, [=]() { const std::string someCopy = stringToPassByValue; }); Now, with the Visual C++ 2010 this code doesn't work. What happens is that the stringToPassByValue is not copied. Instead the "capture by value" feature passes the data by reference. The result is that if the function is executed after stringToPassByValue has gone out of scope, the application crashes as its destructor is called already. So I wonder: is it possible to pass data to a lambda function as a copy? Note: One possible solution would be to modify our framework to pass the data in the lambda parameter declaration list, as follows: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, [=](const std::string stringPassedByValue) { const std::string someCopy = stringPassedByValue; } , stringToPassByValue); However, this solution is so verbose that our original function pointer solution is both shorter and easier to read. Update: The full implementation of AsyncCall is too big to post here. In short, what happens is that the AsyncCall template function instantiates a template class holding the lambda function. This class is derived from a base class that contains a virtual Execute() function, and upon an AsyncCall() call, the function call class is put on a call queue. A different thread then executes the queued calls by calling the virtual Execute() function, which is polymorphically dispatched to the template class which then executes the lambda function.

    Read the article

  • How to pass a Lambda Expression as method parameter with EF

    - by Registered User
    How do I pass an EF expression as a method argument? To illustrate my question I have created a pseudo code example: The first example is my method today. The example utilizes EF and a Fancy Retry Logic. What I need to do is to encapsulate the Fancy Retry Logic so that it becomes more generic and does not duplicate. In the second example is how I want it to be, with a helper method that accepts the EF expression as an argument. This would be a trivial thing to do with SQL, but I want to do it with EF so that I can benefit from the strongly typed objects. First Example: public static User GetUser(String userEmail) { using (MyEntities dataModel = new MyEntities ()) { var query = FancyRetryLogic(() => { (dataModel.Users.FirstOrDefault<User>(x => x.UserEmail == userEmail))); }); return query; } } Second Example: T RetryHelper<T>(Expression<Func<T, TValue>> expression) { using (MyEntities dataModel = new (MyEntities ()) { var query = FancyRetryLogic(() => { return dataModel.expression }); } } public User GetUser(String userEmail) { return RetryHelper<User>(<User>.FirstOrDefault<User>(x => x.UserEmail == userEmail)) }

    Read the article

  • Filtering two arrays to avoid Inf/NaN values

    - by Gacek
    I have two arrays of doubles of the same size, containg X and Y values for some plots. I need to create some kind of protection against Inf/NaN values. I need to find all that pairs of values (X, Y) for which both, X and Y are not Inf nor NaN If I have one array, I can do it using lambdas: var filteredValues = someValues.Where(d=> !(double.IsNaN(d) || double.IsInfinity(d))).ToList(); Now, for two arrays I use following loop: List<double> filteredX=new List<double>(); List<double> filteredX=new List<double>(); for(int i=0;i<XValues.Count;i++) { if(!double.IsNan(XValues[i]) && !double.IsInfinity(XValues[i]) && !double.IsNan(YValues[i]) && !double.IsInfinity(YValues[i]) ) { filteredX.Add(XValues[i]); filteredY.Add(YValues[i]); } } Is there any way of filtering two arrays at the same time using LINQ/Lambdas, as it was done for single array?

    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

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >