将实体列表转换为int数组

时间:2016-08-25 13:33:30

标签: c# entity-framework linq

我需要用60个值类型int填充数组,并且我在数据库中的DbSet中有值。

没有循环,有没有办法将这个List转换为Int []。 该值位于名为temperature

的属性中
public void SetLineChartData()
{
    //Suppose we have a list of 60 items.
    using (ZigBeeContext db = new ZigBeeContext())
    {
        var lista = (from p in db.Medidas
        select new Medida
        {
            Fecha = p.FechaHora
        }).ToList();
    }

    lineChartData = new int[60];
    lineChartData[0] = RandomNumberGenerator.randomScalingFactor();
    hora[0] = DateTime.Now.ToShortTimeString();

    lineChartData[1] = RandomNumberGenerator.randomScalingFactor();
    hora[1] = DateTime.Now.ToShortTimeString();

    lineChartData[2] = RandomNumberGenerator.randomScalingFactor();
    hora[2] = DateTime.Now.ToShortTimeString();

    lineChartData[3] = RandomNumberGenerator.randomScalingFactor();
    hora[3] = DateTime.Now.ToShortTimeString();

    lineChartData[4] = RandomNumberGenerator.randomScalingFactor();
    hora[4] = DateTime.Now.ToShortTimeString();

    lineChartData[5] = RandomNumberGenerator.randomScalingFactor();
    hora[5] = DateTime.Now.ToShortTimeString();

    lineChartData[6] = RandomNumberGenerator.randomScalingFactor();
    hora[6] = DateTime.Now.ToShortTimeString();

    //colorString = "rgba(" + RandomNumberGenerator.randomColorFactor() + "," + RandomNumberGenerator.randomColorFactor() + "," + RandomNumberGenerator.randomColorFactor() + ",.3)";
}

我需要用60个值类型int填充数组,并且我在数据库中的DbSet中有值。

没有循环,有没有办法将这个List转换为Int []。该值位于名为temperature

的属性中

5 个答案:

答案 0 :(得分:3)

不确定你的意思是“不做循环”,因为许多函数会执行循环,即使它们看起来不像它。 如果我理解你想要做什么,那么可能是这样的:

int[] myArray = lista.Select(x => x.temperature).ToArray();

答案 1 :(得分:2)

LINQ可以提供您的要求:

var arr = lista.Select(i => i.Fecha).ToArray();

答案 2 :(得分:2)

使用Linq你可以这样做:

List<MyObject> lst = new List<MyObject>(); // fake dbSet can be Queryable

int[] toto =   lst.Take(60).Select(item => item.MyInt).ToArray();


private class MyObject
{
    public int MyInt { get; set; }
}

答案 3 :(得分:2)

只需使用Linq:

public void SetLineChartData()
{
    int[] yourIntArray; // your int array
    //Suppose we have a list of 60 items.
    using (ZigBeeContext db = new ZigBeeContext())
    {
        var lista = (from p in db.Medidas
                        select new Medida
                        {
                            Fecha = p.FechaHora,
                        }).ToList();
        // here is how you can do that
        yourIntArray = lista.Select(x => 
                        x.FechaHora //i think that's property that you need to be in int array
                        ).ToArray();
    }
}

答案 4 :(得分:2)

如果FechaHora已经不是int了,而你想要施展它,你可以这样做......

int[] lista = db.Medidas.Select(p => p.FechaHora).Cast<int>().ToArray();