LINQ列出<对象>并获得每行值 [英] linq to list<object> and get values per row
问题描述
一个测试,我需要做一个列表的一些参数设置。这个列表不是每个定义预先定义为一个类型和/或什么的吧。
for a test I need to make a list with some parameter settings. This list is not per definition pre-defined as a type and / or what's in it.
bool[] trueOrFalse = new bool[] { true, false };
int[] para1 = new int[] { 1, 2, 3 };
int[] para2 = new int[] { 5, 6, 7 };
int[] para3 = new int[] { 1, 2, 3 };
int[] para4 = new int[] { 5, 7, 9 };
List<object> test = (from a in trueOrFalse
from b in para1
from c in para2
from d in para3
from e in para4
let f = c - d
where c - d <= 3
select new { a, b, c, d, e, f }).AsEnumerable<object>().ToList();
结果是罚款(这只是一个试验),我得到一个列表的所有参数组合有可能,我可以作为其他方法的参数使用。 (我需要它作为一个列表,因为,据我所知,VAR测试不能被解析为一个参数的另一种方法。)
the result is fine (this is just for a test) and I do get a list back with all the parameter combinations possible, which I can use as a parameter for another method. (I need it as a list, because, as far as I know, var test cannot be parsed as a parameter to another method.)
当我徘徊上面的测试调试模式下,我可以看到每一行和每一列包含A到F作为一个单独的领域。
When I hover above test in debug mode, I can see each row and each row contains a to f as a separate field.
但我怎么能减去价值?
让说,我想在列表中使用foreach循环
let say I want to use a foreach loop over the list.
我怎么可以设置INT MYA = A等?
的问候,
how can I set int myA = a etc? regards,
Matthijs
推荐答案
好吧,你'重的明确的调用去除类型的信息 AsEnumerable<对象>
。刚刚摆脱这一点,并使用 VAR
的变量:
Well, you're explicitly removing type information by calling AsEnumerable<object>
. Just get rid of that, and use var
for the variable:
var test = (from a in trueOrFalse
from b in para1
from c in para2
from d in para3
from e in para4
let f = c - d
where c - d <= 3
select new { a, b, c, d, e, f }).ToList();
然后,你可以这样做:
Then you can do:
foreach (var item in test)
{
Console.WriteLine(item.a); // Strongly typed at compile-time
}
现在,我以前曾错过了我可以作为另一种方法的部分参数使用。 (您仍然可以使用列表 - 但它是一个匿名类型的列表)。使用匿名类型,你真的结果传递给一个强类型的方式方法
Now, I had previously missed the "which I can use as a parameter for another method" part. (You can still use a list - but it's a list of an anonymous type.) Using anonymous types, you really pass the result to a method in a strongly-typed way.
选项:
- 创建一个名为类型所有相关的数据,因此你可以把它在形式强类型的方式。
- 为你传递数据的方法使用类型推断的到的(这可能会或可能不会是可行的,目前还不清楚自己在做什么)
- 使用在C#4动态类型绕过正常的静态类型在C#。
- 使用反射访问属性。
- Create a named type with all the relevant data, so you can keep it in that form in a strongly typed way.
- Use type inference for the method that you're passing the data to (that may or may not be feasible; it's not clear what you're doing).
- Use dynamic typing in C# 4 to get around normal static typing in C#.
- Access the properties using reflection.
如果你能告诉我们更多关于你的另一种方法做的事情,这将真正帮助。如果该方法可以使通用的,你可能仍然能够使用匿名类型
If you can tell us more about what you're doing in the other method, that would really help. If the method can be made generic, you may well still be able to use anonymous types.
这篇关于LINQ列出<对象>并获得每行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!