This is my function:
private IEnumerable<string> SeachItem(int[] ItemIds)
{
using (var reader = File.OpenText(Application.StartupPath + #"\temp\A_A.tmp"))
{
var myLine = from line in ReadLines(reader)
where line.Length > 1
let id = int.Parse(line.Split('\t')[1])
where ItemIds.Contains(id)
let m = Regex.Match(line, #"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)")
where m.Success == true
select new { Text = line, ItemId = id, Path = m.Groups[2].Value };
return myLine;
}
}
I get a compile error,because "myLine" is not a IEnumerable[string] and I don't know how to write IEnumerable[Anonymous]
"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable[AnonymousType#1]' to 'System.Collections.Generic.IEnumerable[string]'"
You cannot declare IEnumerable<AnonymousType> because the type has no (known) name at build time. So if you want to use this type in a function declaration, make it a normal type. Or just modify your query to return a IENumerable<String> and stick with that type.
Or return IEnumerable<KeyValuePair<Int32, String>> using the following select statement.
select new KeyValuePair<Int32, String>(id, m.Groups[2].Value)
I am not necessarily recommending this...
It is a kind of subversion of the type system but you could do this:
1) change your method signature to return IEnumerable (the non generic one)
2) add a cast by example helper:
public static class Extensions{
public static IEnumerable<T> CastByExample<T>(
this IEnumerable sequence,
T example) where T: class
{
foreach (Object o in sequence)
yield return o as T;
}
}
3) then call the method something like this:
var example = new { Text = "", ItemId = 0, Path = "" };
foreach (var x in SeachItem(ids).CastByExample(example))
{
// now you can access the properties of x
Console.WriteLine("{0},{1},{2}", x.Text, x.ItemId, x.Path);
}
And you are done.
The key to this is the fact that if you create an anonymous type with the same order, types and property names in two places the types will be reused. Knowing this you can use generics to avoid reflection.
Hope this helps
Alex
The method signature on SearchItem indicates that the method returns an IEnumerable<string> but the anonymous type declared in your LINQ query is not of type string. If you want to keep the same method signature, you have to change your query to only select strings. e.g.
return myLine.Select(a => a.Text);
If you insist on returning the data selected by your query, you can return an IEnumerable<object> if you replace your return statement with
return myLine.Cast<object>();
Then you can consume the objects using reflection.
But really, if your going to be consuming an anonymous type outside the method that it is declared in, you should define a class an have the method return an IEnumerable of that class. Anonymous types are convenience but they are subject to abuse.
Your function is trying to return IEnumerable<string>, when the LINQ statement you are executing is actually returning an IEnumerable<T> where T is a compile-time generated type. Anonymous types are not always anonymous, as they take on a specific, concrete type after the code is compiled.
Anonymous types, however, since they are ephemeral until compiled, can only be used within the scope they are created in. To support your needs in the example you provided, I would say the simplest solution is to create a simple entity that stores the results of your query:
public class SearchItemResult
{
public string Text { get; set; }
public int ItemId { get; set; }
public string Path { get; set; }
}
public IEnumerable<SearchItemResult> SearchItem(int[] itemIds)
{
// ...
IEnumerable<SearchItemResult> results = from ... select new SearchItemResult { ... }
}
However, if your ultimate goal is not to retrieve some kind of object, and you are only interested in, say, the Path...then you can still generate an IEnumerable<string>:
IEnumerable<string> lines = from ... select m.Groups[2].Value;
I hope that helps clarify your understanding of LINQ, enumerables, and anonymous types. :)
Return a ValueTuple instead of an anonymous class. Ex (using "named tuples")-
(Text: line, ItemId: id, Path: m.Groups[2].Value)
https://learn.microsoft.com/en-us/dotnet/csharp/tuples
Instead of-
new { Text = line, ItemId = id, Path = m.Groups[2].Value }
The ValueTuple is part of C# version 7 and was originally implemented as a separate NuGet package (System.ValueTuple). Starting with .NET 4.7 it is a built-in type. For .NET Core, versions prior to 2.0 required the NuGet package but it is built-in with version 2.0.
The question was asked a long time ago, I hope it helps someone...
"You cannot declare IEnumerable", instead, must convert it to a "custom" IEnumerable:
public class MyString
{
public string String { get; set; } = string.Empty;
}
public IEnumerable<MyString> GetMyStrings(List<string> Strings)
{
var AnonString = from S in Strings group S by S into Grouped select new { String = Grouped.Key };
IEnumerable<MyString> Result = AnonString.Select(x => new MyString() { String = x.String }).ToArray();
return Result;
}
Regards.
this link could be useful for others who end up here
https://idreesdotnet.blogspot.com/2019/08/c-how-to-create-list-of-anonymous-type.html
the first solution (of 6) is delightlfully simple
1: First create the object(s) of anonymous type and then pass it to an array and call ToList() method.
var o1 = new { Id = 1, Name = "Foo" };
var o2 = new { Id = 2, Name = "Bar" };
var list = new[] { o1, o2 }.ToList();
Related
I'm getting some JSON as a string and storing it as such:
private static List<object> history = new List<object>();
var data = JsonConvert.DeserializeObject(parsedData);
history.Add(data);
The JSON data looks something like this:
{ id: 12, data: 'my data' }
I'd like to add another method that iterates through the history list, finds an item by its ID and updates it.
What's the best way to access properties on objects like this?
If the incoming JSON string always has the same fields, you can serialize it to a defined class/type.
public class JsonHistory
{
public int id { get; set; }
public string data { get; set; }
}
List<JsonHistory> history = new List<JsonHistory>();
var histData= JsonConvert.DeserializeObject<JsonHistory>(parsedData);
history.Add(histData);
You can also then use linq to find any matches you are looking for:
var matches = history.Where(x => x.id == 10).Select(x => x.data);
You can use dynamic instead of object, because it is easier to use properties rather than object
List<dynamic> history = new List<dynamic>();
string parsedData = "{ id: 12, data: 'my data' }";
var data = JsonConvert.DeserializeObject<dynamic>(parsedData);
history.Add(data);
history.Add(data);
foreach (var o in history)
{
o.id = 13;
}
Also, I strongly suggest you to create a class and use it as known type. That will give you intellisense and definitely you will need that further.
The JSON.NET documentation has the following approach, that I would also suggest using:
First - deserialise to a sensible type (anonymous is fine)
var json = "{id: 12, data: 'my data'}";
var definition = new { Id = 0, Data = "" }
var deserialised = JsonConvert.DeserializeAnonymousType(json, definition);
Second - you've got your first item, so you can "trick" the compiler into letting you use the anonymous type in a list:
var history = (new[] { deserialised }).ToList();
You can then shove any other deserialised instances into that list.
Now you can do your filtering:
var itemImLookingFor = history.SingleOrDefault(x => x.Id == 10);
Once you've then got the item, you can just update it:
itemImLookingFor.Data = itemImLookingFor.Data.ToUpperCase()
I'd recommend reading this as it explains some of the shortcomings inherent in using the dynamic keyword; it's not a bad thing to do, it just has its place.
For this scenario, JSON.NET gives you all the tools you need to either deserialise to a type of your own defining (e.g. write a class that mirrors the JSON, or to an anonymous type like I've done here).
The usual approach is to either deserialize to a custom class or to deserialize to JObject which would allow you to iterate over its properties like using reflection. Both require a lot of typing.
But you can use a clever little trick and get all the benefits of a strong type without having to write the class.
Use an anonymous duck type
Add this method to your library somewhere:
static public T JsonDeserialize<T>(string input, T template)
{
return JsonConvert.DeserializeObject<T>(input);
}
Once you have this in place, you can use it to duck-type the JSON (i.e. get the compiler to infer an anonymous type) by supplying an example instance. This allows you to use anonymous types instead of typing up a custom class.
So for example, to get the row with ID 12, you do something like this:
using System;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
static public T JsonDeserialize<T>(string input, T example)
{
return JsonConvert.DeserializeObject<T>(input);
}
public static void Main()
{
//Sample data with two records
const string input = #"[ { 'id' : 12, 'data' : 'MyData' }, { 'id' : 13, 'data' : 'Another record' } ]";
//Create an example instance so the compiler can use its anonymous type
var example = new []
{
new { id = default(int), data = default(string) }
};
//Pass the example as argument 2 so that the compiler can infer T. The argument itself isn't used for anything.
var list = JsonDeserialize(input, example);
//Now we have a strongly-typed list, without having to write a class
//We can use LINQ or anything else that needs a strong type
foreach ( var o in list.Where( a => a.id == 12) )
{
Console.WriteLine(o.id);
Console.WriteLine(o.data); //Intellisense works here
}
}
}
Output:
12
MyData
Working example on DotNetFiddle.
my code supposed to check two conditions and return the values but when i try to return q this error shows up
Cannot implicitly convert type 'System.Collections.Generic.List<< anonymous type: string Name, string File>>' to 'System.Collections.Generic.List< string>
and i tried everything but nothing worked also don't know to set List<string> or set it as List<EF_Model.PDF> ,PDF is a DTO in my model
this is my code
internal List<string> Customers_File(int _id)
{
using (var Context = new EF_Model.CoolerEntities())
{
var q = from c in Context.Customers
where c.Id == _id &&
c.Ref_PDF != null
select new { c.PDF.Name, c.PDF.File };
return q.ToList();
}
}
You have to convert the anonymous object into a string representation.(Note I'm using C# 6.0 feature - string interpolation, you can replace it with string.Format in the previous versions.
Example:
return q.Select(x=>$"Name = {x.PDF.Name} File = {c.PDF.File}").ToList();
You have declared your return type as string but are returning an a list of anonymous objects with two properties. That won't work. If you want to return a string you need to create a single string per list item. If you want to return object change your return type
You are getting this error because you have defined Customers_File as returning a list of strings. However, the list q that you return doesn't fit that description.
In your query, when you do
select new { c.PDF.Name, c.PDF.File };
..you are making an Anonymous Type, and storing it in the collection q. This type has two fields and is clearly not a string.
Some possible solutions are:
Change your method to have return type List<object> instead of List<string> (not recommended).
Make your object into a string via some form of serialization (JSON or XML).
Create a class or struct for this data and change the return type of your method to List<dataClass>
You need to define an object with your to properties
public class PdfInfo
{
public string Name{get;set;}
public string File{get;set;}
}
Return a list of them from your method
internal List<PdfInfo> Customers_File(int _id)
And finally project to those, in place of an anonymous object:
....
select new PdfInfo() { Name=c.PDF.Name, File = c.PDF.File };
I have a linq query as follow:
public static ViewUserDisplayPreferences GetUserDisplayPreferences(int TheUserID)
{
using ( MyDataContext TheDC = new MyDataContext() )
{
var OutputUserDisplayPreferences = from user in TheDC.Users
where user.UserID == TheUserID
select new ViewUserDisplayPreferences
{
UserTimeFormat = user.UserTimeDisplay
};
return (ViewUserDisplayPreferences)(OutputUserDisplayPreferences);
}
}
For the moment, the object ViewUserDisplayPreferences is defined as follow (more variables will be added later):
public class ViewUserDisplayPreferences
{
public string UserTimeFormat { get; set; }
};
On the return statement at runtime, I get this error:
Unable to cast object of type
'System.Data.Linq.DataQuery`1[ObjectsUsers.ViewUserDisplayPreferences]'
to type
'ObjectsUsers.ViewUserDisplayPreferences'.]
What's wrong with the code? The intellisense is not showing any error on the line?
Thanks
OutputUserDisplayPreferences is an IEnumerable<T>. If you want an object, use either the First (if there can be more than one) or Single (if you know for sure only one object will be in the sequence) method on the sequence. If it is possible for the sequence to be empty, use the respective *OrDefault method.
Linq returns a collection. Try adding a .FirstOrDefault to the end.
I have asked this question about using the a Linq method that returns one object (First, Min, Max, etc) from of a generic collection.
I now want to be able to use linq's Except() method and I am not sure how to do it. Perhaps the answer is just in front on me but think I need help.
I have a generic method that fills in missing dates for a corresponding descriptive field. This method is declared as below:
public IEnumerable<T> FillInMissingDates<T>(IEnumerable<T> collection, string datePropertyName, string descriptionPropertyName)
{
Type type = typeof(T);
PropertyInfo dateProperty = type.GetProperty(datePropertyName);
PropertyInfo descriptionProperty = type.GetProperty(descriptionPropertyName);
...
}
What I want to accomplish is this. datePropertyName is the name of the date property I will use to fill in my date gaps (adding default object instances for the dates not already present in the collection). If I were dealing with a non-generic class, I would do something like this:
foreach (string description in descriptions)
{
var missingDates = allDates.Except(originalData.Where(d => d.Description == desc).Select(d => d.TransactionDate).ToList());
...
}
But how can I do the same using the generic method FillInMissingDates with the dateProperty and descriptionProperty properties resolved in runtime?
I think the best way would be to define an interface with all of the properties that you want to use in your method. Have the classes that the method may be used in implement this interface. Then, use a generic method and constrain the generic type to derive from the interface.
This example may not do exactly what you want -- it fills in missing dates for items in the list matching a description, but hopefully it will give you the basic idea.
public interface ITransactable
{
string Description { get; }
DateTime? TransactionDate { get; }
}
public class CompletedTransaction : ITransactable
{
...
}
// note conversion to extension method
public static void FillInMissingDates<T>( this IEnumerable<T> collection,
string match,
DateTime defaultDate )
where T : ITransactable
{
foreach (var trans in collection.Where( t => t.Description = match ))
{
if (!trans.TransactionDate.HasValue)
{
trans.TransactionDate = defaultDate;
}
}
}
You'll need to Cast your enumeration to ITransactable before invoking (at least until C# 4.0 comes out).
var list = new List<CompletedTransaction>();
list.Cast<ITransactable>()
.FillInMissingDates("description",DateTime.MinValue);
Alternatively, you could investigate using Dynamic LINQ from the VS2008 Samples collection. This would allow you to specify the name of a property if it's not consistent between classes. You'd probably still need to use reflection to set the property, however.
You could try this approach:
public IEnumerable<T> FillInMissingDates<T>(IEnumerable<T> collection,
Func<T, DateTime> dateProperty, Func<T, string> descriptionProperty, string desc)
{
return collection.Except(collection
.Where(d => descriptionProperty(d) == desc))
.Select(d => dateProperty(d));
}
This allows you to do things like:
someCollection.FillInMissingDates(o => o.CreatedDate, o => o.Description, "matching");
Note that you don't necessarily need the Except() call, and just have:
.. Where(d => descriptionProperty(d) != desc)
foreach (string description in descriptions)
{
var missingDates = allDates.Except<YourClass>(originalData.Where(d => d.Description == desc).Select(d => d.TransactionDate).ToList());
}
In fact, almost all LINQ extension in C# have a generic possible value. (Except and Except)
If you're going to identify the property to be accessed by a string name, then you don't need to use generics. Their only purpose is static type safety. Just use reflection to access the property, and make the method work on a non-generic IEnumerable.
Getting Except result with multiple properties working with custom data class is not allowed.
You have to use it like this: (given in msdn 101 LINQ Samples)
public void Linq53()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList();
var productFirstChars =
from p in products
select p.ProductName[0];
var customerFirstChars =
from c in customers
select c.CompanyName[0];
var productOnlyFirstChars = productFirstChars.Except(customerFirstChars);
Console.WriteLine("First letters from Product names, but not from Customer names:");
foreach (var ch in productOnlyFirstChars)
{
Console.WriteLine(ch);
}
}
Having the key, you can handle your data accordingly :)
I would like to generate the following select statement dynamically using expression trees:
var v = from c in Countries
where c.City == "London"
select new {c.Name, c.Population};
I have worked out how to generate
var v = from c in Countries
where c.City == "London"
select new {c.Name};
but I cannot seem to find a constructor/overload that will let me specify multiple properties in my select lambda.
This can be done, as mentioned, with the help of Reflection Emit and a helper class I've included below. The code below is a work in progress, so take it for what it's worth... 'it works on my box'. The SelectDynamic method class should be tossed in a static extension method class.
As expected, you won't get any Intellisense since the type isn't created until runtime. Works good on late-bound data controls.
public static IQueryable SelectDynamic(this IQueryable source, IEnumerable<string> fieldNames)
{
Dictionary<string, PropertyInfo> sourceProperties = fieldNames.ToDictionary(name => name, name => source.ElementType.GetProperty(name));
Type dynamicType = LinqRuntimeTypeBuilder.GetDynamicType(sourceProperties.Values);
ParameterExpression sourceItem = Expression.Parameter(source.ElementType, "t");
IEnumerable<MemberBinding> bindings = dynamicType.GetFields().Select(p => Expression.Bind(p, Expression.Property(sourceItem, sourceProperties[p.Name]))).OfType<MemberBinding>();
Expression selector = Expression.Lambda(Expression.MemberInit(
Expression.New(dynamicType.GetConstructor(Type.EmptyTypes)), bindings), sourceItem);
return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", new Type[] { source.ElementType, dynamicType },
Expression.Constant(source), selector));
}
public static class LinqRuntimeTypeBuilder
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static AssemblyName assemblyName = new AssemblyName() { Name = "DynamicLinqTypes" };
private static ModuleBuilder moduleBuilder = null;
private static Dictionary<string, Type> builtTypes = new Dictionary<string, Type>();
static LinqRuntimeTypeBuilder()
{
moduleBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run).DefineDynamicModule(assemblyName.Name);
}
private static string GetTypeKey(Dictionary<string, Type> fields)
{
//TODO: optimize the type caching -- if fields are simply reordered, that doesn't mean that they're actually different types, so this needs to be smarter
string key = string.Empty;
foreach (var field in fields)
key += field.Key + ";" + field.Value.Name + ";";
return key;
}
public static Type GetDynamicType(Dictionary<string, Type> fields)
{
if (null == fields)
throw new ArgumentNullException("fields");
if (0 == fields.Count)
throw new ArgumentOutOfRangeException("fields", "fields must have at least 1 field definition");
try
{
Monitor.Enter(builtTypes);
string className = GetTypeKey(fields);
if (builtTypes.ContainsKey(className))
return builtTypes[className];
TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable);
foreach (var field in fields)
typeBuilder.DefineField(field.Key, field.Value, FieldAttributes.Public);
builtTypes[className] = typeBuilder.CreateType();
return builtTypes[className];
}
catch (Exception ex)
{
log.Error(ex);
}
finally
{
Monitor.Exit(builtTypes);
}
return null;
}
private static string GetTypeKey(IEnumerable<PropertyInfo> fields)
{
return GetTypeKey(fields.ToDictionary(f => f.Name, f => f.PropertyType));
}
public static Type GetDynamicType(IEnumerable<PropertyInfo> fields)
{
return GetDynamicType(fields.ToDictionary(f => f.Name, f => f.PropertyType));
}
}
The accepted answer is very useful, but I needed something a little closer to a real anonymous type.
A real anonymous type has read-only properties, a constructor for filling in all of the values, an implementation of Equals/GetHashCode for comparing the values of each property, and an implementation ToString that includes the name/value of each property. (See https://msdn.microsoft.com/en-us/library/bb397696.aspx for a full description of anonymous types.)
Based on that definition of anonymous classes, I put a class that generates dynamic anonymous types on github at https://github.com/dotlattice/LatticeUtils/blob/master/LatticeUtils/AnonymousTypeUtils.cs. The project also contains some unit tests to make sure the fake anonymous types behave like real ones.
Here's a very basic example of how to use it:
AnonymousTypeUtils.CreateObject(new Dictionary<string, object>
{
{ "a", 1 },
{ "b", 2 }
});
Also, another note: I found that when using a dynamic anonymous type with Entity Framework, the constructor must be called with the "members" parameter set. For example:
Expression.New(
constructor: anonymousType.GetConstructors().Single(),
arguments: propertyExpressions,
members: anonymousType.GetProperties().Cast<MemberInfo>().ToArray()
);
If you used one of the versions of Expression.New that does not include the "members" parameter, Entity Framework would not recognize it as the constructor of an anonymous type. So I assume that means a real anonymous type's constructor expression would include that "members" information.
Maybe a bit late but may help to someone.
You Can generate dynamic select by call DynamicSelectGenerator in select from an entity.
public static Func<T, T> DynamicSelectGenerator<T>()
{
// get Properties of the T
var fields = typeof(T).GetProperties().Select(propertyInfo => propertyInfo.Name).ToArray();
// input parameter "o"
var xParameter = Expression.Parameter(typeof(T), "o");
// new statement "new Data()"
var xNew = Expression.New(typeof(T));
// create initializers
var bindings = fields.Select(o => o.Trim())
.Select(o =>
{
// property "Field1"
var mi = typeof(T).GetProperty(o);
// original value "o.Field1"
var xOriginal = Expression.Property(xParameter, mi);
// set value "Field1 = o.Field1"
return Expression.Bind(mi, xOriginal);
}
);
// initialization "new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var xInit = Expression.MemberInit(xNew, bindings);
// expression "o => new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var lambda = Expression.Lambda<Func<T, T>>(xInit, xParameter);
// compile to Func<Data, Data>
return lambda.Compile();
}
And use by this code:
var result = dbContextInstancs.EntityClass.Select(DynamicSelectGenerator<EntityClass>());
I don't believe that you will be able to achieve this. Although when you do select new { c.Name, c.Population } it seems like you're not creating a class you actually are. If you have a look at the compiled output in Reflector or the raw IL you will be able to see this.
You'll have a class which would look something like this:
[CompilerGenerated]
private class <>c__Class {
public string Name { get; set; }
public int Population { get; set; }
}
(Ok, I cleaned it up a touch, since a property is really just a get_Name() and set_Name(name) method set anyway)
What you're trying to do is proper dynamic class creation, something which wont be available until .NET 4.0 comes out (and even then I'm not really sure if it'll be able to achieve what you want).
You're best solution would be to define the different anonymous classes and then have some kind of logical check to determine which one to create, and to create it you can use the object System.Linq.Expressions.NewExpression.
But, it may be (in theory at least) possible to do it, if you're getting really hard-core about the underlying LINQ provider. If you are writing your own LINQ provider you can detect if the currently-parsed expression is a Select, then you determine the CompilerGenerated class, reflect for its constructor and create.
Defiantly not a simple task, but it would be how LINQ to SQL, LINQ to XML, etc all do it.
You could use the IQueryable-Extensions here, which is an implemantation of the solution described by "Ethan J. Brown":
https://github.com/thiscode/DynamicSelectExtensions
The Extension builds dynamically an anonymous type.
Then you can do this:
var YourDynamicListOfFields = new List<string>(
"field1",
"field2",
[...]
)
var query = query.SelectPartially(YourDynamicListOfFields);
You could use a parameter class instead of working with an anonymous type. In your example you can create a parameter class like this:
public struct ParamClass {
public string Name { get; set; };
public int Population { get; set; };
}
…and put it into your select like this:
var v = from c in Countries
where c.City == "London"
select new ParamClass {c.Name, c.Population};
What you get out is something of the type IQueryable<ParamClass>.
This compiles, I dunno if it works however...
myEnumerable.Select((p) => { return new { Name = p.Name, Description = p.Description }; });
Assuming p is what your transforming, and the select statement is returning an anon type, using the function declaration of lambda's.
Edit: I also don't know how you would generate this dynamically. But at least it shows you how to use the select lambda to return an anon type with multiple values
Edit2:
You would also have to bare in mind, that the c# compiler actually generates static classes of the anon type. So the anon type does actually have a type after compile time. So if your generating these queries at run time (which I assume you are) you may have to construct a type using the various reflection methods (I believe you can use them to make types on the fly) load the created types into execution context and use them in your generated output.
I think most of the things are already answered - as Slace said, you need some class that would be returned from the Select method. Once you have the class, you can use the System.Linq.Expressions.NewExpression method to create the expression.
If you really want to do this, you can generate class at runtime too. It's a bit more work, because it cannot be done using LINQ Expression trees, but it's possible. You can use System.Reflection.Emit namespace to do that - I just did a quick search and here is an article that explains this:
Introduction to Creating Dynamic Types with Reflection.Emit
You could use the Dynamic Expression API which allows you to dynamically build your select statement like this:
Select("new(<property1>,<property2>,...)");
You need the Dynamics.cs file from the LINQ and language samples for Visual Studio for this to work, both are linked at the bottom of this page. You can also see a working example showing this in action on at the same URL.