在下面的简化示例中,我想在 result
被赋值之前定义它。下面的 linq 查询返回匿名类型的列表。 result
将作为 IEnumerable<'a> 来自 linq 查询,但我无法在方法顶部以这种方式定义它。我尝试做的事情是否可行(在 .NET 4 中)?
bool large = true;
var result = new IEnumerable(); //This is wrong
List<int> numbers = new int[]{1,2,3,4,5,6,7,8,9,10}.ToList<int>();
if (large)
{
result = from n in numbers
where n > 5
select new
{
value = n
};
}
else
{
result = from n in numbers
where n < 5
select new
{
value = n
};
}
foreach (var num in result)
{
Console.WriteLine(num.value);
}
编辑:明确地说,我知道在上面的例子中我不需要匿名类型。这只是用一个简单的小例子来说明我的问题。
最佳答案
匿名类型只能用 var
声明。好处是具有相同属性的匿名类型将是相同的类型。如果你真的需要它(在这个例子中你不需要它)那么你可以写:
var result = Enumerable.Repeat(new {value = 0}, 0); // stub value which will give needed type
if (...)
{
result = ...;
}
else
{
result = ...;
}
P.S.:这甚至在以前的 .Net 版本(低于 4.0)中也是可能的
关于linq - 如何预定义一个包含匿名类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5249870/