这是我的函数:
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;
}
}我得到一个编译错误,因为"myLine“不是IEnumerablestring,而且我不知道如何编写IEnumerableAnonymous
“无法将类型'System.Collections.Generic.IEnumerableAnonymousType#1‘隐式转换为'System.Collections.Generic.IEnumerablestring'”
发布于 2009-05-23 16:36:39
不能声明IEnumerable<AnonymousType>,因为该类型在生成时没有(已知)名称。因此,如果您想在函数声明中使用此类型,请将其设置为普通类型。或者只是修改您的查询以返回一个IENumerable<String>并坚持使用该类型。
或者使用下面的select语句返回IEnumerable<KeyValuePair<Int32, String>>。
select new KeyValuePair<Int32, String>(id, m.Groups[2].Value)发布于 2009-05-23 17:06:13
我不一定要推荐这个...它是类型系统的一种颠覆,但您可以这样做:
1)更改您的方法签名以返回IEnumerable (非泛型签名)
2)添加cast by example帮助器:
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)然后调用方法,如下所示:
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);
}你就完了。
关键在于,如果您创建一个具有相同顺序的匿名类型,则类型和属性名在两个位置将被重用。了解了这一点,您可以使用泛型来避免反射。
希望这能帮助亚历克斯
发布于 2009-05-23 16:39:11
SearchItem上的方法签名指示该方法返回IEnumerable<string>,但在LINQ查询中声明的匿名类型不是string类型。如果你想保持相同的方法签名,你必须改变你的查询来只选择string。
return myLine.Select(a => a.Text);如果坚持返回查询选择的数据,并且将return语句替换为,则可以返回IEnumerable<object>
return myLine.Cast<object>();然后,您可以使用反射来使用对象。
但实际上,如果您要在声明匿名类型的方法之外使用它,则应该定义一个类,并让该方法返回该类的IEnumerable。匿名类型很方便,但容易被滥用。
https://stackoverflow.com/questions/901854
复制相似问题