我在主页上有几个网站并加载文章。我可以在文章上设置排名,以不同的顺序显示它们,但文章的各个网站的排序可能不同。
我必须订购文章的代码为所有网站设置相同的订单:
string officeLocation = "";
// office location could be either World, Europe, Africa, America, Asia, Pacific
var result = articles.Select(a => new
{
Title = a.Title,
Url = a[SPBuiltInFieldId.FileRef],
Byline = a[Constants.FieldNames.Byline],
ArticleDate = a[Constants.FieldNames.ArticleStartDate],
RankWorld = a[Constants.FieldNames.World],
RankEurope = a[Constants.FieldNames.RankEurope],
RankAfrica = a[Constants.FieldNames.RankAfrica],
RankAmerica = a[Constants.FieldNames.RankAmerica],
RankAsia = a[Constants.FieldNames.RankAsia],
RankPacific = a[Constants.FieldNames.RankPacific],
});
rptArticles.DataSource = result.OrderBy(a => a.RankWorld);
rptArticles.DataBind();
代码将所有排名设置为RankWorld(1-6)。
如果字符串officeLocation
(传递给方法)是欧洲,那么我想按a.RankEurope
排序,如果officeLocation是a.RankAsia
的亚洲顺序,依此类推。< / p>
我怎样才能最好地实现这一目标(.NET 3.5)?
提前致谢。
答案 0 :(得分:2)
假设您有一组固定的位置(按照定义,您必须拥有匿名类型),那么您可以使用一个开关:
string officeLocation = "";
// office location could be either World, Europe, Africa, America, Asia, Pacific
var result = articles.Select(a => new
{
Title = a.Title,
Url = a[SPBuiltInFieldId.FileRef],
Byline = a[Constants.FieldNames.Byline],
ArticleDate = a[Constants.FieldNames.ArticleStartDate],
RankWorld = a[Constants.FieldNames.World],
RankEurope = a[Constants.FieldNames.RankEurope],
RankAfrica = a[Constants.FieldNames.RankAfrica],
RankAmerica = a[Constants.FieldNames.RankAmerica],
RankAsia = a[Constants.FieldNames.RankAsia],
RankPacific = a[Constants.FieldNames.RankPacific],
});
switch (officeLocation)
{
case "World": result = result.OrderBy(a => a.RankWorld); break;
case "Europe": result = result.OrderBy(a => a.RankEurope); break;
case "Africa": result = result.OrderBy(a => a.RankAfrica); break;
case "America": result = result.OrderBy(a => a.RankAmerica); break;
case "Asia": result = result.OrderBy(a => a.RankAsia); break;
case "Pacific": result = result.OrderBy(a => a.RankPacific); break;
default: throw new Exception("Unexpected location: " + officeLocation);
}
rptArticles.DataSource = result.OrderBy(a => a.RankWorld);
rptArticles.DataBind();
显然,您需要决定如何最好地处理意外的位置。
请注意,理想情况下,我刚刚将OrderBy
功能分配给Func<T,R>
,但只有一个OrderBy
来电,但由于此处你不能这样做匿名类型。