2013-01-24 19 views
0

我有下面的類:如何從列表<ClassName>製作兩個字符串數組(名稱,值)?

class Node 
{ 
    public string NameField{ get; set; } 
    public string ValueField{ get; set; } 
} 

,也有節點作爲var test = new List<Node>的名單,我需要兩個字符串數組作爲string[],首先包含了所有的名稱字段和第二包含所有ValueField,我做了下面的代碼:

string[] NameField = new string[test.Count]; 
    string[] ValueField = new string[test.Count]; 
    int i = 0; 
    foreach (var s in prefsNameValueArray) 
    { 
     NameField[i] = s.CTMAttrName; 
     ValueField[i] = s.CTMAttrValue; 
     i++; 
    } 

我可以做使用LINQ同樣的,任何人可以幫助我提高這個代碼?

由於提前, RAMZY

回答

2

使用LINQ:

string[] NameFields = nodes.Select(n => n.NameField).ToArray(); 
string[] ValueFields = nodes.Select(n => n.ValueField).ToArray(); 

LINQ的不一定是這裏最有效的方式,因爲ToArray可以創建這可能是過大的數組(由於加倍算法)如果您使用查詢而不是集合。但它簡短易讀(主要是速度很快)。

這是for循環版本:

int count = nodes.Count(); // in case you want to change the collection type or use a linq query 
string[] NameField = new string[count]; 
string[] ValueField = new string[count]; 
for (int i = 0; i < count; i++) 
{ 
    NameField[i] = nodes.ElementAt(i).NameField; 
    ValueField[i] = nodes.ElementAt(i).ValueField; 
} 
1
var nameField = test.Select(n => n.CTMAttrName).ToArray(); 
var valueField = test.Select(n => n.CTMAttrValue).ToArray(); 
1

使用Lambda expressions;

string[] NameField = prefsNameValueArray.Select(x=> x.NameField).ToArray(); 
string[] ValueField = prefsNameValueArray.Select(x=> x.ValueField).ToArray(); 
相關問題