I'm working on a database abstaction for mongodb in .NET Core 2.1. For this I use the mongo driver from Nu-Get.   Now I'm working on a simple generic extension method to include referenced objects in a similar way like other database abstractions for relational databases do that.  The following example shows how I plan to get a customer collection and include the  related job offers:  //get the customer collection and include the related job offers var result = Database.Customers.Find(x =&gt; x.Id != null).Include(x =&gt; x.JobOffers);   And this is the code of the Include extension method:  public static IList&lt;T&gt; Include&lt;T&gt;(this IFindFluent&lt;T, T&gt; result, Expression&lt;Func&lt;T, object&gt;&gt; filter)     {         var propertyName = filter.Body.ToString().Split(".")[1];         var idFieldName = typeof(T).Name.Substring(0, typeof(T).Name.Length) + "Id";          var list = new List&lt;T&gt;();         foreach (dynamic item in result.ToList())         {             try             {                 var type = item.GetType().GetProperty(propertyName).PropertyType.GenericTypeArguments[0];                 var builder = Builders&lt;JobOffer&gt;.Filter;                 var queryFilter = builder.Eq(idFieldName, (string)item.Id);                 var prop = item.GetType().GetProperty(propertyName);                  var relatedItems = _database.GetCollection&lt;JobOffer&gt;(propertyName).Find(queryFilter).ToList();                 prop.SetValue(item, relatedItems);              }             catch (Exception e)             {              }             list.Add(item);          }         return list;     }   So far it works but as it is now it just works for the object with the type JobOffers and it should work for any type of objects.   So my Question is: In the try {} section there is a variable type where the needed class is stored as Type.  How can I use this type in the angle brackets? I 'd like to do something like this:  var type = item.GetType().GetProperty(propertyName).PropertyType.GenericTypeArguments[0]; var builder = Builders&lt;type&gt;.Filter; var relatedItems = _database.GetCollection&lt;type&gt;(propertyName).Find(queryFilter).ToList();   But I get the error: type is a variable but is used as a type.  How am I suppost to solve this?
80627
I have a string variable that represents the name of a custom class. Example:   string s = "Customer";   I will need to create an arraylist of customers. So, the syntax needed is:  List&lt;Customer&gt; cust = new ..    How do I convert the string s to be able to create this arraylist on runtime?
11195
I found an example in the  for Dynamic LINQ that allows you to use a sql-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable&lt;T&gt;. Is there any way to get this functionality on IEnumerable&lt;T&gt;?
20538
I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class.  Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text").  Here's the syntax for creating an extension method for StringBuilder:  public static class sbExtensions {     public static StringBuilder blah(this StringBuilder sb)     {         return sb;     } }    It successfully adds the blah extension method to the StringBuilder.  Unfortunately, operator overloading does not seem to work:  public static class sbExtensions {     public static StringBuilder operator +(this StringBuilder sb, string s)     {         return sb.Append(s);     } }    Among other issues, the keyword this is not allowed in this context.  Are adding operator overloads via extension methods possible?  If so, what's the proper way to go about it?
123645
According to the documentation  in order to retrieve a list of picklist values for an object we need to pass in a Record Type Id which can be retrieved using the getObjectInfo method.   The issue is that these are both wire functions and I cannot figure out how to chain these methods.  If I try code like the following:  getObjectInfo({ objectApiName: ACCOUNT_OBJECT })             .then(result =&gt; {                 return getPicklistValues({recordTypeId: result.defaultRecordTypeId, fieldApiName: TYPE_FIELD});             })             .then(result =&gt; {                 this.picklistValues = result.data             })             .catch(error =&gt; {                 this.error = error;             });   I get an error      render threw an error in 'c:getpicklistexample' [Imperative use is not   supported. Use @wire(getObjectInfo).]   If I try something like   @track rtId;      @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })     handleResult({error, data}) {         if(data) {             this.rtId = data.defaultRecordTypeId;         }     }      @wire(getPicklistValues, {recordTypeId: this.rtId,fieldApiName: TYPE_FIELD})     picklistValues;   Then it throws an internal server error. Anybody have an idea as to how I could retrieve the record type Id and then call to get the pick list values like the documentation suggests?  FYI my imports are:  import { LightningElement, wire, track } from 'lwc'; import { getPicklistValues, getObjectInfo } from 'lightning/uiObjectInfoApi'; import TYPE_FIELD from '@salesforce/schema/Account.Type'; import ACCOUNT_OBJECT from '@salesforce/schema/Account';
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.
105044
This might be a old question: Why does IEnumerable&lt;T&gt; inherit from IEnumerable?  This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable&lt;T&gt;, I have to write two GetEnumerator() functions, one for IEnumerable&lt;T&gt; and the other for IEnumerable.  And, IList&lt;T&gt; doesn't inherit from IList.   I don't know why IEnumerable&lt;T&gt; is designed in other way.
115473
Assuming I have a left outer join as such:  from f in Foo join b in Bar on f.Foo_Id equals b.Foo_Id into g from result in g.DefaultIfEmpty() select new { Foo = f, Bar = result }   How would I express the same task using extension methods? E.g.  Foo.GroupJoin(Bar, f =&gt; f.Foo_Id, b =&gt; b.Foo_Id, (f,b) =&gt; ???)     .Select(???)
82389
I have a contact in a generic sObject in apex and while I'm able to easily get detail field values using   sObject.get('MyContactField__c')  I'm not able to get fields off the related parent object, and I'm sure the related field is in memory, based on the debug logs. This returns a runtime error:  sObject.get('Account.MyAccountField__c')  with the error     Invalid field Account.MyAccountField__c' for Contact   How do I get a field value off of a parent on a generic sObject?
31102
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code.   var urls = new List&lt;string&gt;(); urls.Add("http://www.google.com");  foreach (string url in urls) {     // Get all links from the url     List&lt;string&gt; newUrls = GetLinks(url);      urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping }   How can I rewrite this in a better way? I'm guessing a recursive solution?
42901
I'd like to run a query using the EntityFieldQuery object. I need value from both the node and node_access table therefore I'd need to use INNER JOIN. From the d.o documentation I can't figure out how this is possible.  Here's what I have --  $query = new EntityFieldQuery(); $result = $query-&gt;entityCondition('entity_type', 'node') -&gt;entityCondition('bundle', 'node_access') -&gt;propertyCondition('type', 'external_link') -&gt;propertyCondition('status', 1) -&gt;fieldCondition('gid', '3', '=') -&gt;fieldCondition('realm', 'domain_id', '=') -&gt;fieldCondition('grant_view', '1', '&gt;=') -&gt;range(0,1) -&gt;execute();
34531
Using LINQ to SQL, I have an Order class with a collection of OrderDetails.  The Order Details has a property called LineTotal which gets Qnty x ItemPrice.   I know how to do a new LINQ query of the database to find the order total, but as I already have the collection of OrderDetails from the DB, is there a simple method to return the sum of the LineTotal directly from the collection?  I'd like to add the order total as a property of my Order class. I imagine I could loop through the collection and calculate the sum with a for each Order.OrderDetail, but I'm guessing there is a better way.
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.
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 .
6902
Let's say I have a generic member in a class or method, like so: public class Foo&lt;T&gt; {     public List&lt;T&gt; Bar { get; set; }          public void Baz()     {         // get type of T     }    }  When I instantiate the class, the T becomes MyTypeObject1, so the class has a generic list property: List&lt;MyTypeObject1&gt;. The same applies to a generic method in a non-generic class: public class Foo {     public void Bar&lt;T&gt;()     {         var baz = new List&lt;T&gt;();                  // get type of T     } }  I would like to know what type of objects the list of my class contains. So what type of T does the list property called Bar or the local variable baz contain? I cannot do Bar[0].GetType(), because the list might contain zero elements. How can I do it?
36086
I'm using C# on Framework 3.5.  I'm looking to quickly sort a Generic List&lt;T&gt;.  For the sake of this example, let's say I have a List of a Person type with a property of lastname.  How would I sort this List using a lambda expression?  List&lt;Person&gt; people = PopulateList(); people.OrderBy(???? =&gt; ?????)
76755
I have a bit of code where I've written a SOQL query that returns a list of SObject records, however I need a Set&lt;Id&gt; structure to pass to another method that I don't have control of (and thus can't change the method signature of).  How can I turn my returned List&lt;SObject&gt; into a Set&lt;Id&gt;? Is the best option just a for loop?
22371
I write a sample query to fetch account Ids from cases of a particular record type.Then i wrote another sample query parent to child relationship to fetch opportunity ids from accounts.  My sample code  List&lt;Case&gt; c=new List&lt;Case&gt;(); c=[Select Id,accountId from case where RecordTypeId = '01290000000sF3L']; List&lt;Id&gt; accountIds= new List&lt;Id&gt;(); List&lt;Account&gt; accounts=new List&lt;Account&gt;(); List&lt;Opportunity&gt; opps=new List&lt;Opportunity&gt;(); for(Case cl:c)  { accountIds.add(cl.accountId); } accounts=[Select Id,name,(select Id,name from opportunities) from account        where Id in:accountIds]; System.debug('Data in accounts '+accounts);   But my issue is how to get opportunity id from above Soql accounts means how to add those opportunity id's to the list.  for(Account ao:accounts) { //How to fetch Opportunity ids from above account list. }