我正在嘗試運行一個查詢,其中“GroupBy”子句將根據例如將資料系結到組合框等的列舉值對結果進行不同的分組。
我嘗試使用 switch case 來執行此操作,但這導致在“GroupBy”子句上出現編譯器錯誤 CS0411,因為據我了解,從 lambda 回傳的物件的型別將根據執行的情況而有所不同。
我怎樣才能巧妙地實作這個功能?
我在下面附上了一個最小的問題示例,作為控制臺程式。
class Program
{
static List<Person> People;
enum GroupBy
{
Month,
Year
}
static void Main(string[] args)
{
People = new List<Person>();
People.Add(new Person()
{
Dob = new DateTime(2000,10,1),
Name = "James",
IsSelected = false
});
People.Add(new Person()
{
Dob = new DateTime(2000, 5, 1),
Name = "Anne",
IsSelected = true
});
People.Add(new Person()
{
Dob = new DateTime(2000, 5, 23),
Name = "Bob",
IsSelected = true
});
People.Add(new Person()
{
Dob = new DateTime(1999, 1, 15),
Name = "Kate",
IsSelected = false
});
// Obviously, in the real thing, the grouping value would be
// databound to a combobox or something.
GroupBy grouping = GroupBy.Month;
var groups = People
.OrderBy(x => x.Dob)
.GroupBy(x => /* PROBLEM LINE - Gives compiler error CS0411 */
{
switch(grouping)
{
case GroupBy.Month:
return new { x.Dob.Year, x.Dob.Month };
case GroupBy.Year:
return new { x.Dob.Year};
default:
throw new Exception("No can do");
}
});
Console.WriteLine("Grouping is: " grouping "\r\n");
foreach(var group in groups)
{
Console.WriteLine("Group: " group.Key);
foreach(Person p in group)
{
Console.WriteLine("\t" p.Name ", " p.Dob);
}
Console.WriteLine("");
}
Console.ReadKey();
}
}
public class Person
{
public DateTime Dob { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
uj5u.com熱心網友回復:
回傳匿名型別時,您的 switch 陳述句中會出現問題。編譯器無法推斷型別(因為它是由編譯器為每個單獨的投影生成的)并因此引發錯誤。
您可以通過創建包裝類輕松解決此問題:
public class GroupedResult
{
public int Year { get; set; }
public int Month { get; set; }
}
var groups = People
.OrderBy(x => x.Dob)
.GroupBy(x => /* PROBLEM LINE - Gives compiler error CS0411 */
{
switch (grouping)
{
case GroupBy.Month:
return new GroupedResult { Year = x.Dob.Year, Month = x.Dob.Month };
case GroupBy.Year:
return new GroupedResult { Year = x.Dob.Year };
default:
throw new Exception("No can do");
}
});
或者通過確保兩個匿名型別上存在相同的屬性,從而產生相同的編譯器生成的型別:
var groups = People
.OrderBy(x => x.Dob)
.GroupBy(x => /* PROBLEM LINE - Gives compiler error CS0411 */
{
switch (grouping)
{
case GroupBy.Month:
return new { Year = x.Dob.Year, Month = x.Dob.Month };
case GroupBy.Year:
return new { Year = x.Dob.Year, Month = 0 };
default:
throw new Exception("No can do");
}
});
uj5u.com熱心網友回復:
最簡單的解決方案:
.GroupBy(x => new
{
Year = x.Dob.Year,
Month = grouping == GroupBy.Month ? x.Dob.Month : 0
};
Year始終是您分組的一部分Monthgrouping僅當等于時才會成為您分組的一部分Month- 否則使用常量 << ergo 沒有分組
我建議避免在GroupBy委托內拋出例外。
- 而是進行初步檢查并提前退出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431552.html
