I'm struggling to build an expression tree so I can dynamically do filtering on some data.  I have come up with this, but it fails at the var lambda = line  foreach (var rule in request.Where.Rules) {     var parameterExpression = Expression.Parameter(typeof(string), rule.Field);     var left = Expression.Call(parameterExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));     var right = Expression.Constant(rule.Data.ToLower());     var method = typeof(string).GetMethod("Contains", new [] { typeof(string) });     var call = Expression.Call(left, method, right);     var lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(call, parameterExpression);     query = query.Where(lambda); }   The var rule has a Field (ex "Name") which I want to compare with the text in rule.Data (ex 'tom').  So if T.Name.Contains("tom"); I want the query to include the record, otherwise, not.  The var query is of type IQueryable&lt;T&gt;  EDIT: Finally got it working with this code:  foreach (var rule in request.Where.Rules) {     var parameter = Expression.Parameter(typeof(T), "x");     var property = Expression.Property(parameter, rule.Field);     var value = Expression.Constant(rule.Data);     var type = value.Type;      var containsmethod = type.GetMethod("Contains", new[] { typeof(string) });     var call = Expression.Call(property, containsmethod, value);     var lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(call, parameter);     query = query.Where(lambda); }
124087
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:  t =&gt; t.SomeProperty.Contains("stringValue");   So far I have got:      private static Expression.Lambda&lt;Func&lt;string, bool&gt;&gt; GetContainsExpression&lt;T&gt;(string propertyName, string propertyValue)     {         var parameterExp = Expression.Parameter(typeof(T), "type");         var propertyExp = Expression.Property(parameter, propertyName);         var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)         ...         return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(containsMethodExp, parameterExp); //then something like this     }   I just don't know how to reference the String.Contains() method.  Help appreciated.
123190
I have a List&lt;int&gt; and a List&lt;customObject&gt;. The customObject class has an ID property. How can I get a List&lt;customObject&gt; containing only the objects where the ID property is in the List&lt;int&gt; using LINQ?  Edit: I accepted Konrads answer because it is easier/more intuitive to read.
26779
Lets say I have an array like this:  string [] Filelist = ...   I want to create an Linq result where each entry has it's position in the array like this:  var list = from f in Filelist     select new { Index = (something), Filename = f};   Index to be 0 for the 1st item, 1 for the 2nd, etc.  What should I use for the expression Index= ?
36756
Is there a pattern using Linq to dynamically create a filter?  I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.
12935
Is there a way to Deserialize Expressions in C#, I would like to store Expressions in a Database and load them at run time.
34626
the soql in the following code is failing. The error message is: "Compile failure on line 6, column 5: Unexpected token '&lt;'."   Map&lt;Id, String&gt; profileIds = new Map&lt;Id, String&gt;(); profileIds.put('00eee000000xxxx','System Administrator'); profileIds.put('00eee00000yyyyy','YYY Profile'); profileIds.put('00eee00000zzzzz','ZZZ Profile');  List&lt;User&gt; users = [SELECT Id, Name, Email, ProfileId FROM User WHERE NOT(Email like '%@example.com') AND ProfileId NOT IN :profileIds.keySet()]; System.debug(users.size()); for (User usr: users) {     System.debug(usr.id+'    '+usr.Email); }   When I run the Query in SOQL Editor, it says "unexpected token: AND"  SELECT Id, Name, Email, ProfileId FROM User WHERE NOT(Email like '%@example.com') AND  ProfileId NOT IN ('00eee000000xxxx','00eee00000yyyyy','00eee000000zzzz')   When I remove one of the clauses from the where statement, it works. I do not understand whats wrong with the query. I tried wrapping the query with in parenthesis too, but no luck. for example   List&lt;User&gt; users = [SELECT Id, Name, Email, ProfileId FROM User WHERE (NOT(Email like '%@example.com') AND ProfileId NOT IN :profileIds.keySet())];  List&lt;User&gt; users = [SELECT Id, Name, Email, ProfileId FROM User WHERE (NOT(Email like '%@example.com') AND (ProfileId NOT IN :profileIds.keySet()))];
80615
I am working on code generation and ran into a snag with generics. Here is a "simplified" version of what is causing me issues.  Dictionary&lt;string, DateTime&gt; dictionary = new Dictionary&lt;string, DateTime&gt;(); string text = dictionary.GetType().FullName;   With the above code snippet the value of text is as follows:   System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,   Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.DateTime, mscorlib,   Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]   (Line breaks added for better readability.)  Is there a way to get the type name (type) in a different format without parsing the above string? I desire the following result for text:  System.Collections.Generic.Dictionary&lt;System.String, System.DateTime&gt;
81739
If I have a Linq to SQL expression like this:    from subscription in dbContext.Subscriptions  where subscription.Expires &gt; DateTime.Now select subscription   I want this to to use the SQL Servers GETDATE() function instead of the time of the machine running the C# program.  The next question would be how to translate this:  DateTime.Now.AddDays(2)   to this:  DATEADD(dd, 2, GETDATE())
25761
I need to evaluate a mathmatical expression that is presented to me as a string in C#.  Example noddy but gets the point across that the string as the expression.  I need the evaluate to then populate an int.  There is no Eval() in C# like in others langugaes...  String myString = "3*4";   Edit:  I am on VS2008   Tried the Microsoft.JScript. = Its deprecated method (but still complies - warning)  However the Microsoft.JScript dll that I have doens work on      public object InvokeMember(string   name, BindingFlags invokeAttr, Binder   binder, object target, object[] args);   Complains that there is a missing ";"  go figure...  EDIT 2  Solution - was the codeDom one - it worked for as there are no security issue - only me ever going to be running the code.  Many thanks for the replies ...  And the link to the new Dragon Book  awesome   EDIT 3  Matt dataTable.Compute() also works - even better for the security conscious.  (parameter checking noted)
60664
Parameterized Queries in .Net always look like this in the examples:  SqlCommand comm = new SqlCommand(@"    SELECT *     FROM   Products     WHERE  Category_ID = @categoryid ",     conn); comm.Parameters.Add("@categoryid", SqlDbType.Int); comm.Parameters["@categoryid"].Value = CategoryID;   But I'm running into a brick wall trying to do the following:  SqlCommand comm = new SqlCommand(@"    SELECT *     FROM   Products     WHERE  Category_ID IN (@categoryids)        OR  name LIKE '%@name%' ",     conn); comm.Parameters.Add("@categoryids", SqlDbType.Int); comm.Parameters["@categoryids"].Value = CategoryIDs; comm.Parameters.Add("@name", SqlDbType.Int); comm.Parameters["@name"].Value = Name;   Where   CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes) Name is a string, possibly with single quotes and other bad characters   What's the right syntax for this?
4045
What is the most efficient way to write the old-school:  StringBuilder sb = new StringBuilder(); if (strings.Count &gt; 0) {     foreach (string s in strings)     {         sb.Append(s + ", ");     }     sb.Remove(sb.Length - 2, 2); } return sb.ToString();   ...in LINQ?
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
32517
For example I have such query:  Query q = sess.createQuery("from Cat cat"); List cats = q.list();   If I try to make something like this it shows the following warning   Type safety: The expression of type List needs unchecked conversion to conform to List&lt;Cat&gt;   List&lt;Cat&gt; cats = q.list();   Is there a way to avoid it?
1725
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)  static T FindThing&lt;T&gt;(IList collection, int id) where T : IThing, new() {     foreach T thing in collecion     {         if (thing.Id == id)             return thing;     }     return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead. }   This gives me a build error      "Cannot convert null to type parameter   'T' because it could be a value type.   Consider using 'default(T)' instead."   Can I avoid this error?
118445
I am trying to write a condition into a SQL WHERE clause that forces the column comparison to a variable to be compared in lowercase. However the addExpression function isn't accomplishing this (since that is putting the expression in the field selection, not the where clause.  Here is what I have tried:  $category = 'mobile wifi'; $query = db_select('taxonomy_term_data', 'ttd')     -&gt;fields('ttd', array('tid')); $query-&gt;innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid'); $query-&gt;addExpression("LOWER(ttd.name) = $category"); $result = $query-&gt;condition('machine_name', 'images_cat', '=')     -&gt;execute()     -&gt;fetchAssoc();   And this:  $category = 'mobile wifi'; $query = db_select('taxonomy_term_data', 'ttd')     -&gt;fields('ttd', array('tid')); $query-&gt;innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid'); $result = $query-&gt;condition('machine_name', 'images_cat', '=')     -&gt;condition('LOWER(ttd.name)', $category, '=')     -&gt;execute()     -&gt;fetchAssoc();   The second one becomes invalid and the first one causes the problem I mentioned above. Any thoughts or suggestions?  Thanks, Patrick
15230
example:  public static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items) {    items.Keys.Each(key =&gt; {       if (items[key] **is IEnumerable&lt;?&gt;**) { /* do something */ }       else { /* do something else */ } }   Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable&lt;> implements IEnumerable?