作者J002 (阿里山 我来了XD~)
看板C_Sharp
标题Re: [问题] class 中的field转string array
时间Wed Apr 8 21:40:12 2015
※ 引述《gundan (弹弹的哀伤)》之铭言:
: 请问一下
: 我现在有个class如下
: class Test
: {
: public string AAA{get;set;}
: public string BBB{get;set;}
: }
: 再来有个test的list
: List<Test> test;
: 最後是有个string list
: List<List<string>> output;
: 我要把AAA的内容放到output[0]
: BBB放到output[1];
: 我现在只想到
: output[0] = test.Select(x=>x.AAA).ToList<string>();
: output[1] = test.Select(x=>x.BBB).ToList<string>();
: 如果我这个class中的field有 十个我就要写十行
: 觉得有点麻烦耶!
: 有没有什麽写法可以再缩减的啊?
: 谢谢大家!
感谢YahooTaiwan大大给予提示…
先把你的class Test改成下面…
因为叫AAA BBB 要打三个字有点麻烦= =a
public class TestForRef
{
public string A1 { get; set; }
public string A2 { get; set; }
public string A3 { get; set; }
public string A4 { get; set; }
public string A5 { get; set; }
public string A6 { get; set; }
public string A7 { get; set; }
}
测试方法:
[Fact]
public void TestRef()
{
var test = new List<TestForRef>
{
new TestForRef
{
A1 = "01",
A2 = "02",
A3 = "03",
A4 = "04",
A5 = "05",
A6 = "06",
A7 = "07"
},
new TestForRef
{
A1 = "11",
A2 = "12",
A3 = "13",
A4 = "14",
A5 = "15",
A6 = "16",
A7 = "17"
}
};
var output = new List<List<string>>();
test.ForEach(testForRef =>
{
var listInOutput = new List<string>();
var props = testForRef.GetType().GetProperties();
props.ToList().ForEach(prop =>
{
listInOutput.Add(prop.GetValue(testForRef).ToString());
});
output.Add(listInOutput);
});
Assert.True(output[1][2] == "13");
}
您再看看是不是您要的…
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 118.165.117.30
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1428500415.A.940.html
※ 编辑: J002 (118.165.117.30), 04/08/2015 21:41:08
※ 编辑: J002 (118.165.117.30), 04/08/2015 21:41:22
1F:推 YahooTaiwan: 正解,可以顺便加个 property 型别判断 04/08 23:41
2F:推 gundan: 谢谢推文和回文的前辈,搞定了! 04/09 01:00
3F:→ nfsong: 有看有推 04/11 20:22