循环遍历C#集合

时间:2016-07-21 08:38:38

标签: c# collections

我有一个班级和方法

public class Datas
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
 public void Funnel()
    {
        string commandText = "select sc.stagename, count(cs.stages_id) as StageCount from currentstage cs inner join stagesconfig sc on cs.stages_id = sc.stages_id group by cs.stages_id,sc.stagename";


        string constrings = WebConfigurationManager.ConnectionStrings["Data"].ToString();

        SqlConnection myConn = new SqlConnection(constrings);
        SqlCommand myComm = new SqlCommand(commandText, myConn);

        myConn.Open();
        List<Datas> fruitinfo = new List<Datas>();

        SqlDataReader reader = myComm.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                fruitinfo.Add(new Datas
                {
                    Name = reader.GetValue(0).ToString(),
                    Value = Convert.ToInt32(reader.GetValue(1))
                });

            }

        }

如何循环通过fruitinfo列表以数组的形式保存它。数组必须与此表单类似。用于替换数据括号中的项目与fruitinfo循环列表

    Data = new Data(new object[]
                {
                    new object[] { "Website visits", 10000 },
                    new object[] { "Downloads", 5000 },
                    new object[] { "Requested price list", 2000 },
                    new object[] { "Invoice sent", 1000 },
                    new object[] { "Finalized", 500 }
                }),

3 个答案:

答案 0 :(得分:2)

var myArray = fruitinfo.Select(x => new object[] { x.Name, x.Value }).ToArray();

并将其与Data - 对象一起使用。

Data = new Data(myArray);

答案 1 :(得分:1)

var myArray = fruitinfo.Select(d => new object[] { d.Name, d.Value }).ToArray();

答案 2 :(得分:0)

我不太清楚为什么你需要生成一个匿名对象数组,但你可以使用字典。

private static void Funnel()
    {
        var datas = new List<Datas>
                        {
                            new Datas { Name = "Website visits", Value = 10000 },
                            new Datas { Name = "Downloads", Value = 5000 },
                            new Datas { Name = "Requested price list", Value = 2000 },
                            new Datas { Name = "Invoice sent", Value = 1000 },
                            new Datas { Name = "Finalized", Value = 500 }
                        };

        var data = datas.ToDictionary(datas1 => datas1.Name, datas1 => datas1.Value);
        foreach (var item in data)
        {
            Console.WriteLine(string.Format("{0}, {1}",item.Key, item.Value));
        }

        var arry = data.ToArray();
        foreach (var item in arry)
        {
            Console.WriteLine(string.Format("{0}, {1}", item.Key, item.Value));
        }
    }

Output