如何将linq结果分配给多维数组

时间:2012-02-16 08:49:40

标签: c# arrays linq

我想将linq结果分配给多维数组,下面是我的代码,任何人都可以告诉我我做错了什么。

var query = (from b in db.FourBodyImages
             where b.Status == true
             orderby b.CreaedDate descending
             select new { b.BodyImage, b.Description, b.HeaderName }
           ).Take(4).ToArray();

if(query.Count()>0)
{
    string[,,] x = new string[4, 4,4];
    x[,,] = query;

    for (int i = 0; i < query.Length; i++)
    {

        if (i == 0)
        { 
            imgBody1.ImageUrl = "FourBodyImages/" + x[0,0,0].ToString();
        }
        if (i == 1)
        {
            imgBody2.ImageUrl = "FourBodyImages/" + x[1,1,1].ToString();
        }
        if (i == 2)
        {
            imgBody3.ImageUrl = "FourBodyImages/" + x[2,2,2].ToString();
        }
        if (i == 3)
        {
            imgBody4.ImageUrl = "FourBodyImages/" + x[3,3,3].ToString();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

目前尚不清楚为什么要开始使用三维数组。你只需要4个值...为什么这不只是一个一维数组?

var query = (from b in db.FourBodyImages
             where b.Status == true
             orderby b.CreaedDate descending
             select new { b.BodyImage, b.Description, b.HeaderName }
             ).Take(4).ToArray();

var bodies = new[] { imgBody1, imgBody2, imgBody3, imgBody4 };
for (int i = 0; i < query.Length; i++)
{
    // Or whichever property you're interested in...
    bodies[i].ImageUrl = "FourBodyImages/" + query[i].BodyImage;
}

如果这没有用,请告诉我们您实际想要达到的目标。例如,为什么查询返回三个属性,以及如何使用它们?

答案 1 :(得分:0)

如果你只需要从数据库中获取4个对象,然后使用它们来填充4个图像,那么你需要做的就是:

//this generates an array of (up to 4) objects of an anonymous type
var query = (from b in db.FourBodyImages
                     where b.Status == true
                     orderby b.CreaedDate descending
                     select new { b.BodyImage, b.Description, b.HeaderName }
                   ).Take(4).ToArray();

//no need for count, we can use the array's length
if (query.Length < 4)
{
   //i have no idea about your requirements, 
   //but if we have less than 4 images - panic
   throw new InvalidOperationException()
}

//no need for the "for-if", that's an anti-patern
imgBody1.ImageUrl = "FourBodyImages/" + query[0].BodyImage;
imgBody2.ImageUrl = "FourBodyImages/" + query[1].BodyImage;
imgBody3.ImageUrl = "FourBodyImages/" + query[2].BodyImage;
imgBody4.ImageUrl = "FourBodyImages/" + query[3].BodyImage;