c# - Using anonymus IEnumerable type -
this may simple question can not figure out...
if have code,
ienumerable myvar = (from in mylist select new { newtext= i.text, newvalue = i.value });
how can user values in myvar (without changing type(ienumerable
))?
like
foreach (var in myvar) { //i.... }
edit :
my actual code returns ienumerable
public ienumerable getdata(ienumerable<int> pricedetailid) { .... return (from in mylist select new { newtext= i.text, newvalue = i.value }); }
then need use result in loop..
var result = getdata(); foreach (var in result) { //i.... }
you can't, because enumerator of ienumerable
returns instances of type object
. first need cast actual type. since type anonymous, can't that.
change type of myvar
var
make work:
var myvar = in mylist select new { newtext= i.text, newvalue = i.value };
however, return
in - illegal - code, indicates linq query inside method returns result , that's reason why want keep ienumerable
.
in case, using anonymous type not correct approach, because leads exact problem having.
should create simple class , use in query , change return type ienumerable<yourclass>
finally, if insist on using anonymous type , ienumerable
, can make use of dynamic
keyword inside foreach
loop:
foreach(dynamic in myvar) { console.writeline(i.newvalue); }
however, no longer have compile time safety, if have typo when accessing dynamic variable runtime exception instead of compiler error.
example: console.writeline(i.foo);
compile although there no foo
property in anonymous type. upon execution however, throw runtimebinderexception
.
Comments
Post a Comment