Using ConvertAll to convert a List of an Object to a List of another Object
Let’s say you have two classes, one called Car and one called Automobile. Inside Car you have a method that performs an explicit conversion of an Automobile to a Car:
public static explicit operator Car(Automobile automobile)
{
return new Car {
Name = automobile.Name,
Make = automobile.Make,
Model = automobile.Model,
Year = automobile.Year
};
}
Now, say we also want a method that will take a List<Automobile> and convert it to a List<Car>. Instead of doing something like this:
public static List ConvertToCar(this List automobiles)
{
List cars = new List();
foreach(var a in automobile) {
cars.Add((Car) a);
}
return cars;
}
We can simplify it to this:
public static List ConvertToCar(this List automobiles)
{
return automobiles.ConvertAll(a=>(Car) a);
}
Simulating SQL’s SELECT * In Salesforce
So after spending some time tinkering with trying to write a query along the lines of SELECT * FROM Contact and continuously getting an error, I realized the Salesforce doesn’t use the asterisk to retrieve all fields for a given object. Therefore, I had to take the long way around writing a query for selecting all fields.
First, we are going to be using DescribeSObject in SforceService to get a list of all fields for a given object. Note that Contact should be replaced with whatever your object is.
DescribeSObjectResult describeSObjectResult =
binding.describeSObject("Contact");
Once we have that, we are going to loop through that array and append it with a comma until we have a string with all of our fields.
public string GetAllFieldsForObject(DescribeSObjectResult describeSObjectResult)
{
StringBuilder fields = new StringBuilder();
for(int i = 0; i < describeSObjectResult.fields.Length; i++)
{
fields.Append(describeSObjectResult.fields[i].name);
if( i != describeSObjectResult.fields.Length - 1)
{
fields.Append(", ");
}
return fields.ToString();
}
}
Now, we can use that string in out SELECT statement, like so:
string query =
String.Format("SELECT {0} FROM {1}", GetAllFieldsForObject(describeSObjectResult), myObject);