开发者

How do i do the following using LINQ feature of C#?

I need help with the following statement to be converted to lambda statement 开发者_JS百科how do i do it?

for (int row = 0; row < rows; row++)
{
    for (int column = 0; column < columns; column++)
    {
        gList.Add(new G(this, new L(row, column), 0, 20, 30));
    }
}

thanks for all the help!!!


var gList = Enumerable.Range(0, rows)
    .SelectMany(row =>
        Enumerable.Range(0, columns)
            .Select(column => new G(this, new L(row, column), 0, 20, 30)
        )
    ).ToList() or .ToArray();

SelectMany will flatten the Enumerable returned from the Select into an IEnumerable.


var gList = from row in Enumerable.Range(0, rows)
            from col in Enumerable.Range(0, columns)
            select new G(this, new L(row, col), 0, 20, 30)

My favourite for inline cartesians like this


List<G> gList = Enumerable.Range(0, rows)
    .SelectMany(row => Enumerable.Range(0, columns)
        .Select(col => new G(this, new L(row, col), 0, 20, 30)))
    .ToList();


Give me the indexes, project each index to a new L, project each L to a new G and assign the resulting sequence of objects to a list named gList.

var indexes = from row in Enumerable.Range(0, rows)
              from column in Enumerable.Range(0, columns)
              select new { Row = row, Column = column };
var ls = indexes.Select(index => new L(index.Row, index.Column));
var gs = ls.Select(l => new G(this, l, 0, 20, 30)).ToList();
var gList = gs.ToList();

Note that if gList is an existing list that you want to add to you can replace the last line by

gList.AddRange(gs);

It reads exactly like what it is doing.


As you can see from the other answers, using lambdas don't always result in cleaner code. Unless you have a specific reason for using lambdas in this case, I would leave the for loops as is.

Readability should be your primary concern, but I imagine using a normal for loop might be slightly faster because you don't have the overhead of function calls, but the difference in most cases won't matter.


Putting everything into one single expression would lead to terrible code. Why would you do that? Does the following help: (untested, out of my head)

public IEnumerable<L> GenerateLs(int rows, int columns)
{
    for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns; column++)
        {
            yield return new L(row, column);
        }
    }
}

gList.Add(l => GenerateLs(rows,columns).Select(new G(this,l,0,20,30)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜