开发者

passing a List<{Anon:string}> to a function in C#

Given:

A linq expression that returns anonymous type with one field which is a string:

var list = new List<MyClass>();
var myStringList = (from myClass in list
                  select new {myClass.StringField}).ToList();
var processedStrings = processStrings(myStringList);

and a function that I pass a List<string> to:

List<string> processStrings(List<string> string开发者_如何学编程sToProcess) {}

Problem:

I get the following compiler error when passing myStringList:

ArgumentType type 'System.Collections.Generic.List<{StringField:string}>' is not assignable to parameter type 'System.Collections.Generic.List<string>'

So I tried to fix this using .Cast<string>() which eliminates the compiler error but throws an exception that it can't cast an Anonymous string to a string.

Any ideas with out having to process each string by hand?


try do not return anonymous object with one string but string itself:

var list = new List<MyClass>();
var myStringList = (from myClass in list
              select myClass.StringField).ToList();
var processedStrings = processStrings(myStringList);


Why not

select myClass.StringField


The "new {myClass.StringField}" creates an anonymous type with a string property...

You should try:

var list = new List<MyClass>();
var myStringList = (
from myClass in list                  
select myClass.StringField).ToList();
var processedStrings = processStrings(myStringList);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜