2011-11-10 38 views
2

我是新來的c#,但不是編程。首先,非常感謝你的幫助!C#如何創建類的列表

我想要一個類或結構體,其中有3個變量是適當的。一個字符串和兩個日期時間。

我想創建一個循環,在列表中存儲新類。

喜歡的東西:

在DataViewer的
每個項目創建新類
分配變量列表
店類
未來

非常感謝你的幫助

+0

你需要哪些幫助?定義一個班級?實例化類?創建一個循環?創建一個列表?如果你向我們展示了你的嘗試,這將有所幫助。 – Chris

+4

這個問題的驚人的部分是,有5(嚴重)的答案 –

+0

這是因爲大家在這裏巖! – CodingIsAwesome

回答

8

你可以用LINQ很容易地做到這一點:

var list = dataViewer 
    .Select(item => new YourClass 
    { 
     StringProperty = ..., 
     DateTimeProperty1 = ..., 
     DateTimeProperty2 = ... 
    }) 
    .ToList(); 

它可以讓你的國家,你的意圖,而不強調力學背後(循環等)(創建於dataViewer每個itemYourClass對象的列表)

編輯:如果你不需要一個列表,只是一個序列,這也使用查詢語法看起來不錯(相同的含義):

var yourClasses = 
    from item in dataViewer 
    select new YourClass 
    { 
     StringProperty = ..., 
     DateTimeProperty1 = ..., 
     DateTimeProperty2 = ... 
    }; 
+1

事實上,除非你特別希望它是一個List而不僅僅是一個IEnumerable,否則你並不特別需要ToList()。 –

+0

@Mike Goodwin:好點。我更新了我的答案,以包含您建議的版本。 –

6

也許像這樣的東西

var list = new List<YourClass>(); 

foreach(var item in dataViewer) { 
    var cls = new YourClass(); 
    // Assign variables here 
    // cls.Test = item.Test; 

    list.Add(cls); 
} 
+0

所以我甚至不需要使用指針在C#中完成此操作?它只會知道我想要做什麼? – CodingIsAwesome

+0

不,你不! :) –

+0

我可以說,雖然我有一個不同的問題,但這是幫助我理解創建輸出json類的列表的問題的答案。謝謝! – CoreyH

1
public class Appropriate 
{ 
    public string Value { get; set; } 
    public DateTime Start { get; set; } 
    public DateTime End { get; set; } 
} 

IList<Appropriate> list = new List<Appropriate>(); 

foreach(var item in dataViewer) { 
    list.Add(new Appropriate() { 
     Value = item["value"], 
     Start = item["start"], 
     End = item["end"] 
    }); 
} 

IList<Appropriate> list = new List<Appropriate>(); 

dataViewer.ToList().ForEach(i => list.Add(new Appropriate() { 
    Value = item["value"], 
    Start = item["start"], 
    End = item["end"] 
}); 
1
public class Foo 
{ 
    public Foo(string name, DateTime dt1, DateTime dt2) 
    { 
     Name = name; 
     DT1 = dt1; 
     DT2 = dt2; 
    } 

    public string Name { get; set; } 
    public DateTime DT1 { get; set; } 
    public DateTime DT2 { get; set; } 
} 

public class Example 
{ 
    public List<Foo> example(DataView dataViewer) 
    { 
     var foos = new List<Foo>();   

     foreach(var data in dataViewer) 
     { 
      foos.Add(new Foo(data.Name, data.DT1, data.DT2); 
     } 

     return foos; 
    } 
} 
3

試試這個:

public class YourClass 
{ 
    public string YourString {get; set;} 
    public DateTime YourDate1 {get; set;} 
    public DateTime YourDate2 {get; set;} 

    public YourClass(string s, DateTime d1, DateTime d2) 
    { 
     YourString = s; 
     YourDate1 = d1; 
     YourDate2 = d2; 
    } 
} 

public List<YourClass> Read() 
{ 
    List<YourClass> list = new List<YourClass>(); 
    foreach(var item in dataViewer) 
     list.Add(new YourClass(s,d1,d2)); // Read variables from item... 
    return list; 
}