I'm in the process of refactoring some code, attempting to make it more self-documenting.  The current code has a query over an OData service which looks like this:  return context.MessageLog.Where (     x =&gt;      (         x.Status == MessageStatus.Success          || x.Status == MessageStatus.Failure     )      &amp;&amp; x.Direction == MessageDirection.Inbound      &amp;&amp; x.ResponseDate == new DateTimeOffset(new DateTime(1900, 01, 01)) );   I'm hoping to change this to make use of Linq Expressions. I could move all of the logic into a single expression and have code run context.MessageLog.Where(MessageIsPendingResponse);. However, I'd like to create expressions for the different conditions: MessageIsProcessed (i.e. now at success or failure state), MessageIsInbound and ResponseNotYetSent (response date is null). I could combine these with multiple where statements like so:  return context.MessageLog     .Where(MessageLogExpression.MessageIsProcessed)     .Where(MessageLogExpression.MessageIsInbound)     .Where(MessageLogExpression.ResponseNotYetSent);   (MessageLogExpression being a class I use to contain these predefined expressions).  Question 1  Is this the best way to combine the satements, or does it risk filtering on the wrong field first (e.g. does Linq combine all the conditions into a single query and allow the query engine (in SQL terms) to determine the best execution plan; or are we forcing it to filter on the Status field first?  Question 2  The above is great for scenarios where we have an AND joining our expressions; but how would we do an OR? I assume there's some way to combine these, but couldn't find anything obvious.  I suspect something like this exists?  return context.MessageLog.Where(new OrExpression(MessageIsSuccess,MessageIsFailure));   Question 3  Is there a good way to combine expressions within another expression defintion; e.g. something like the below code (only a version that compiles)?   public static Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; MessageIsPendingResponse {     get     {         Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; expr = x =&gt;              MessageIsProcessed(x)              &amp;&amp; MessageIsInbound(x)              &amp;&amp; ResponseNotYetSent(x);         return expr;     } }     Addendum: Code for those expressions described above:  public class MessageLogExpression {     public static Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; MessageIsProcessed     {         get         {             Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; expr = x =&gt;              (                 x.Status == MessageStatus.Success                  || x.Status == MessageStatus.Failure             );             return expr;         }     }     public static Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; MessageIsInbound     {         get         {             Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; expr = x =&gt;                  x.Direction == MessageDirection.Inbound;             return expr;         }     }     static readonly DateTimeOffset NullDate = new DateTimeOffset(new DateTime(1900, 01, 01));     public static Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; ResponseNotYetSent     {         get         {             Expression&lt;Func&lt;MessageLogRecord, bool&gt;&gt; expr = x =&gt;                  x.ResponseDate == NullDate; //todo: test if this works or if I have to define the value within the expression             return expr;         }     } }
20981
I have two expressions of type Expression&lt;Func&lt;T, bool&gt;&gt; and I want to take to OR, AND or NOT of these and get a new expression of the same type  Expression&lt;Func&lt;T, bool&gt;&gt; expr1; Expression&lt;Func&lt;T, bool&gt;&gt; expr2;  ...  //how to do this (the code below will obviously not work) Expression&lt;Func&lt;T, bool&gt;&gt; andExpression = expr AND expr2
110962
public static IQueryable&lt;TResult&gt; ApplySortFilter&lt;T, TResult&gt;(this IQueryable&lt;T&gt; query, string columnName)   where T : EntityObject {   var param = Expression.Parameter(typeof(T), "o");   var body = Expression.PropertyOrField(param,columnName);    var sortExpression = Expression.Lambda(body, param);   return query.OrderBy(sortExpression); }   Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:  var sortExpression = Expression.Lambda&lt;T, TSortColumn&gt;(body, param);   Or  return query.OrderBy&lt;T, TSortColumn&gt;(sortExpression);   I don't think this is possible however as TSortColumn can only be determined during runtime.  Is there a way around this?
11106
LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code.  However, the fluent syntax seems to come much more natural to me than the query expression syntax.  var title = entries.Where(e =&gt; e.Approved)     .OrderBy(e =&gt; e.Rating).Select(e =&gt; e.Title)     .FirstOrDefault();  var query = (from e in entries              where e.Approved              orderby e.Rating              select e.Title).FirstOrDefault();   Is there any difference between the two or is there any particular benefit of one over other?
40361
I'm trying to create a query which uses a list of ids in the where clause, using the Silverlight ADO.Net Data Services client api (and therefore Linq To Entities). Does anyone know of a workaround to Contains not being supported?  I want to do something like this:  List&lt;long?&gt; txnIds = new List&lt;long?&gt;(); // Fill list   var q = from t in svc.OpenTransaction         where txnIds.Contains(t.OpenTransactionId)         select t;     Tried this:  var q = from t in svc.OpenTransaction where txnIds.Any&lt;long&gt;(tt =&gt; tt == t.OpenTransactionId) select t;   But got "The method 'Any' is not supported".
82914
I have some dynamic SOQL code in which I'd like to identify whether a method argument is a collection or a single value:  SObject[] query(SObjectType sobType, String field, Object data) {     // Want to know if data is a collection e.g. set or list     // that requires an "in" or a single value that requires     // an "=" in the query. (May also need to use separate bind variables.) }   I note that the sort of check shown immediately below seems to require an exact match for the type of the collection (Id in this case to return true) which is not what I want:  Object o = new Set&lt;Id&gt;(); System.debug(o instanceof Set&lt;Id&gt;);   Is there a simple way to make this determination?  (Yes there are various other ways to code this; checking first to see if there is a direct solution.)  PS  Looks like great caution is needed when using .
29132
I'm looking at creating a basic ORM (purely for fun), and was wondering, is there a way to return the list of tables in a database and also the fields for every table?  Using this, I want to be able to loop through the result set (in C#) and then say for each table in the result set, do this (e.g. use reflection to make a class that will do or contain xyz).  Further to this, what are some good online blogs for SQL Server? I know this question is really about using system SPs and databases in Sql Server, and I am ok with general queries, so I'm interested in some blogs which cover this sort of functionality.  Thanks
91991
Note: Mathematical expression evaluation is not the focus of this question.  I want to compile and execute new code at runtime in .NET.  That being said...  I would like to allow the user to enter any equation, like the following, into a text box:  x = x / 2 * 0.07914 x = x^2 / 5   And have that equation applied to incoming data points.  The incoming data points are represented by x and each data point is processed by the user-specified equation.  I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:  float ApplyEquation (string equation, float dataPoint) {     // parse the equation string and figure out how to do the math     // lots of messy code here... }   When you're processing boatloads of data points, this introduces quite a bit of overhead.  I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once.  It would look something like this:  FunctionPointer foo = ConvertEquationToCode(equation); .... x = foo(x);  // I could then apply the equation to my incoming data like this   Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.  The app would basically be writing new code at run time.  Is this possible with .NET?
19285
I've often had to load multiple items to a particular record in the database. For example: a web page displays items to include for a single report, all of which are records in the database (Report is a record in the Report table, Items are records in Item table). A user is selecting items to include in a single report via a web app, and let's say they select 3 items and submit. The process will add these 3 items to this report by adding records to  a table called ReportItems (ReportId,ItemId).  Currently, I would do something like this in in the code:  public void AddItemsToReport(string connStr, int Id, List&lt;int&gt; itemList) {     Database db = DatabaseFactory.CreateDatabase(connStr);      string sqlCommand = "AddItemsToReport"     DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);      string items = "";     foreach (int i in itemList)         items += string.Format("{0}~", i);      if (items.Length &gt; 0)         items = items.Substring(0, items.Length - 1);      // Add parameters     db.AddInParameter(dbCommand, "ReportId", DbType.Int32, Id);     db.AddInParameter(dbCommand, "Items", DbType.String, perms);     db.ExecuteNonQuery(dbCommand); }   and this in the Stored procedure:  INSERT INTO ReportItem (ReportId,ItemId) SELECT  @ReportId,           Id FROM     fn_GetIntTableFromList(@Items,'~')   Where the function returns a one column table of integers.  My question is this: is there a better way to handle something like this? Note, I'm not asking about database normalizing or anything like that, my question relates specifically with the code.
9803
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I have a collection of records, like a List&lt;sObject&gt; or the Trigger.new context variable. I need to query other records that are related to these records either directly or indirectly, and I want to use the related data to make further updates. When I write a query in a loop, like for (Account a : Trigger.new) {     Account parent = [SELECT Name FROM Account WHERE Id = :a.ParentId];     // ... }  I keep hitting Salesforce query limits, and I know this is not best practice. What can I do to avoid this problem and bulkify my code?
44272
EDIT:  I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type.  Why do I need to do this?  EDIT #2:  The "Values" property is a .NET dictionary of type &lt;TMetadata, TData&gt;.  I have this generic method:  private void FillMetadata&lt;TMetadata, TData&gt;     (Metadata&lt;TMetadata, TData&gt; oMetadata) where TMetadata : IMetadataType {     IMetadataType o;     oMetadata.Values.Add(o, (TData)(object)GetValue()); }   I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).  My question is, why doesn't this compile?  The compile error is on the Add() method:  "cannot convert from 'IMetadataType' to 'TMetadata'."  Isn't that what the "where" clause on the method is for?  What am I missing?
53785
So, every time I have written a lambda expression or anonymous method inside a method that I did not get quite right, I am forced to recompile and restart the entire application or unit test framework in order to fix it. This is seriously annoying, and I end up wasting more time than I saved by using these constructs in the first place. It is so bad that I try to stay away from them if I can, even though Linq and lambdas are among my favourite C# features.  I suppose there is a good technical reason for why it is this way, and perhaps someone knows? Furthermore, does anyone know if it will be fixed in VS2010?  Thanks.
1105
I have never had the need to do this before today, but it doesn't seem like you can make OR queries with EntityFieldQuery, since db_or is used for select queries.  An example would get to all entities that has a date field where the value is null or after today.  Am I missing something or some trick or is this simply not supported?
30132
What I want to do is something like this: I have enums with combined flagged values.  public static class EnumExtension {     public static bool IsSet&lt;T&gt;( this T input, T matchTo )          where T:enum //the constraint I want that doesn't exist in C#3     {             return (input &amp; matchTo) != 0;     } }   So then I could do:  MyEnum tester = MyEnum.FlagA | MyEnum.FlagB  if( tester.IsSet( MyEnum.FlagA ) )     //act on flag a   Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.  Does anyone know a workaround?
38005
Hello I'm trying to use string in SOQL query where clause for multiselect picklist.  I need to get records of CustObj__c where Multipicklist__c fild have 'abc' or 'xyz' values.  String str = '\'abc\',\'xyz\''; for(CustObj__c cust : [Select Id, Name, Multipicklist__c FROM CustObj__c WHERE Multipicklist INCLUDES (:str)]{ somelogic }   However I get no records.  What is wrong in this query?  Ok I tried using list too, here I'm getting all record of all Public Groups where user is assign. and saving those Public Groups names in   List&lt;String&gt; groupIds = new List&lt;String&gt;(); List&lt;String&gt; groupNames = new List&lt;String&gt;();  for(GroupMember gm :[SELECT Id,GroupId,UserOrGroupId FROM GroupMember WHERE UserOrGroupId = :userIds[0]]){             groupIds.add(gm.GroupId);         }         for(Group g :[SELECT ID,Name FROM Group WHERE Id IN :groupIds]){             groupNames.add('\'' + g.Name + '\'');         }  for(CustObj__c cust : [Select Id, Name, Multipicklist__c FROM CustObj__c WHERE Multipicklist INCLUDES (:groupNames)]){ somelogic }   It still not working  I get error in Dev console : Invalid bind expression type of List for column of type String
37203
To all the expert SOSL gurus lurking out there, I thought this will be an interesting one:  I have some SObjects of different types and I want to return their Name values in a single query.  In advance, I know the IDs and the ObjectTypes of the records whose Names I wish to retrieve. It seems 'wrong' to make several SOQL queries even though there aren't too many types.  So being a good platform citizen, I'm using   to retrieve what I need in a single query:  List&lt;List&lt;SObject&gt;&gt; sobjectsLists = Search.query(     'FIND {*?*} RETURNING ' +     'CustomOne__c (Name WHERE Id IN (\'a01000000000000AAA\')),' +     'CustomTwo__c (Name WHERE Id IN (\'a02000000000000AAB\')),' +     'CustomThr__c (Name WHERE Id IN (\'a03000000000000AAC\'))' ); System.debug(sobjectsLists);   But there is one problem: I must specify at least one FIND character and {*?*} doesn't cut it.     System.SearchException search term must be longer than one character: ?   I've tried this to no avail: {*a* OR *b* OR *c* OR *d* OR *e* OR ...} but even if that did work, it wouldn't help in the case that some twisted cowboy puts underscore (_) or god forbid umlaut (ä).  Any guidance on how I can get the Name of all these records at once?
54579
Is there a tool out there which can convert SQL syntax to LINQ syntax?   I just want to rewrite basic queries with join, etc., to . It would save me a lot of time.
790
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.  How do you represent the following in LINQ to SQL:  select DealerContact.* from Dealer  inner join DealerContact on Dealer.DealerID = DealerContact.DealerID