问题
Possible Duplicate:
Accessing C# Anonymous Type Objects
Working with C# Anonymous Types
I'm using linq to entities to get id and full name from a table with customers.
public IQueryable RegresaClientesPorEmpresa(int id_emp)
{
var clientes = from c in context.clientes
where c.IDEmpresa == id_emp
select new
{
c.IDCliente,
NomComp = c.Nombres +" "+ c.ApellidoP +" "+ c.ApellidoM
};
return clientes;
}
The result is used as the datasource of a combobox, then when SelectionChangeCommitted is triggered in my combo, I want the selected item to be added to a listbox:
var clientes = operaciones.RegresaClientesPorEmpresa(2);
combo_cliente.DataSource = clientes;
combo_cliente.DisplayMember = "NomComp";
combo_cliente.ValueMember = "IDCliente";
listBox_grupo.DisplayMember = "NomComp";
listBox_grupo.ValueMember = "IDCliente";
private void combo_cliente_SelectionChangeCommitted(object sender, EventArgs e)
{
listBox_grupo.Items.Add(combo_cliente.SelectedItem);
}
Until here everything is fine. Finally I want to get all "IDCliente"'s values from all items added to my listbox, the problem is that I don't know how to do it because every item is an Anonymous data type. Can anyone help me?
回答1:
The scope of an anonymous type is limited to the method in which it is "declared" (well it's not really declared, but you see what I mean). If you want to use the result of your query in another method, create a named type to hold the results.
回答2:
You shouldn't return anonymous types from your methods if you're expecting to access their properties. It'll be easier on you if you define a class instead, because that establishes the contract of your method.
回答3:
just create a class to avoid anonymous type.
class Foo
{
public string NomComp {get ; set;}
public string IDCliente {get ; set;}
}
and do
select new Foo
{
...
}
to save some hassle.
or You can define
T Cast<T>(object obj, T type)
{
return (T)obj;
}
and then use
object anonymousObject = GetSelection();
var selection = Cast(anonymousObject , new { IDCliente="", NomComp ="" });
and then you should be able to do selection.NomComp
to get the property value.
来源:https://stackoverflow.com/questions/7614912/get-back-anonymous-type