开发者

Type inference with control statements

var sortQ = filterQ;  // <--- update

if (iSortingCols > 0)
{
    sortQ = (sortDirs[0] == "asc") ?
        sortQ.OrderBy((d) => d.GetColumnData()[sortCols[0]]) :
        sortQ.OrderByDescending((d) => d.GetColumnData()[sortCols[0]]);

    if (iSortingCols > 1)
    {
        for (int i = 1; i < iSortingCols; i++)
        {
            sortQ = (sortDirs[i] == "asc") ?
                sortQ.ThenBy(d => d.GetColumnData()[sortCols[i]]) :
                sortQ.ThenByDescending(d => d.GetColumnData()[sortCols[i]]);

        }
     }
 }

The compiler underlines the two results of the ternary op开发者_Python百科erator inside the for loop, saying that IEnumerable<...> doesn't have a method overload called ThenBy (and similarly for ThenByDescending), but the sortQ will be an IOrderedEnumerable<...> in that block. Why isn't C# type inference picking that up?

Update: for those who might have been confused before, what I left out of the original snippet was that I was assigning sortQ to the result of another query which forced the type inference engine to type sortQ as an IEnumerable<..>, which of course is what was screwing up my example. The answer below is the way around this. Thanks to @Marc for reading between the lines.


I'm guessing sortQ is IEnumerable<T>; you need an IOrderedEnumerable<T> to use ThenBy; fortunately, your first OrderBy returns this, so just catch that:

var result = (sortDirs[0] == "asc") ?
    sortQ.OrderBy((d) => d.GetColumnData()[sortCols[0]]) :
    sortQ.OrderByDescending((d) => d.GetColumnData()[sortCols[0]]);

if (iSortingCols > 1)
{
    for (int i = 1; i < iSortingCols; i++)
    {
        result = (sortDirs[i] == "asc") ?
            result.ThenBy(d => d.GetColumnData()[sortCols[i]]) :
            result.ThenByDescending(d => d.GetColumnData()[sortCols[i]]);

    }
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜