简体   繁体   English

创建匿名类的集合

[英]Create Collection of Anonymous Class

I'm writing a bit of code, and I'd like to play with doing it using the anonymous features of C#. 我正在编写一些代码,我想使用C#的匿名功能来玩。

I'm writing a summary based on a DataTable returned from the SQL Server. 我正在根据从SQL Server返回的DataTable编写摘要。

There are many ways I could write it already knowing Classical C# (???), but I'm interested in having a little fun. 我已经知道古典C# (???),有很多方法可以编写它,但是我对获得一些乐趣很感兴趣。

So, here are the type of anonymous classes I want to have: 因此,这是我想要的匿名类的类型:

// Employee
var emp = new {
  Badge = "000000",
  Name = "No Name",
  Parts = new List<Part>(),
  Days = new List<DateTime>(),
};

// Part
var part = new {
  SerialNumber = "N/A",
  Date = DateTime.MinValue,
  Badge = "000000",
};

Now, as I iterate over my DataTable entries, I want to sort my Parts by SerialNumber . 现在,当我遍历DataTable条目时,我想按SerialNumber对我的部件进行排序。

The first thing I have to do is break the data down into days. 我要做的第一件事是将数据分解成几天。

private void TestMethod(DateTime minDate, DateTime maxDate, DataTable table) {
  int days = 1;
  var nextDay = minDate.AddHours(24);
  foreach (DataRow row in table.Rows) {
    var dateTime = (DateTime)row["Date_Time"];
    var emp = new {
      Badge = row["Badge"].ToString(),
      Parts = new List<Part>(),
      Days = new List<DateTime>(),
    };
    var part = new {
      SerialNumber = row["Serial_Number"].ToString(),
      Date = dateTime,
      Badge = row["Badge"].ToString(),
    };
    if (nextDay < dateTime) {
      days++;
      nextDay = nextDay.AddHours(24);
    }
  }

Now, it is getting a little interesting. 现在,它变得有点有趣了。

I need a way to store Part information for the different days and the different employees found for the period. 我需要一种方法来存储该期间不同日期和不同员工的零件信息。

How would I create and use an anonymous collection of my anonymous class items? 如何创建和使用匿名类项目的匿名集合?

var parts = new List<typeof(part)>();
var emps = new List<typeof(emp)>();

Using typeof (above) does not work! 使用typeof (以上)不起作用!

What does? 什么事

You need to use type inference: 您需要使用类型推断:

new[] { part }.ToList()

(you probably want to clear the list afterwards) (您之后可能希望清除列表)

You can also make a helper method: 您还可以创建一个辅助方法:

public static List<T> ListOf<T>(T sample) {
    return new List<T>();
}
var parts = ListOf(part);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM