我可以使用匿名类型更简洁地表达这一点吗?

时间:2011-10-28 22:29:20

标签: c# linq anonymous-types

switch(ID)
{
    case "CustomReportsContainer":
        foreach (var report in SessionRepository.Instance.CustomReports.ToList())
        {
            var reportItem = new RadListBoxItem(report.Name, report.ID.ToString());
            if (!Items.Any(item => int.Equals(item.Value, reportItem.Value)))
            {
                Items.Add(reportItem);
            }
        }
        break;
    case "HistoricalReportsContainer":
        foreach (var report in SessionRepository.Instance.HistoricalReports.ToList())
        {
            var reportItem = new RadListBoxItem(report.Name, report.ID.ToString());
            if (!Items.Any(item => int.Equals(item.Value, reportItem.Value)))
            {
                Items.Add(reportItem);
            }
        }
        break;
}

HistoricalReports和CustomReports是不同类型的集合,但我对每种对象类型的相同两个属性感兴趣。我认为我应该能够使用LINQ的Select,并创建一个匿名类型对象列表。

但是,如果不分配它,我无法创建隐式类型变量。因为我在一个Switch语句的范围内...我不能在switch语句中分配var,然后将其余的代码移到switch语句之外。

我该如何表达这段代码?当前的实施是“最好的”吗?

Uggh,关闭。我能用这个做点什么吗?这是通过我们的API,所以我不能更深入地修改。

ReportServices.GetAllCustomReports().Select(report => new { report.Name, report.ID} ).ToList().ForEach(customReport => _customReports.Add(customReport));

Error   2   Argument 1: cannot convert from 'AnonymousType#1' to 'CableSolve.Web.Dashboard.IReport'

3 个答案:

答案 0 :(得分:4)

CustomReportHistoricalReport应实现IReport接口,其中包含IdName属性(至少)。

switch(ID)
{
    case "CustomReportsContainer":
        AddReportItems(SessionRepository.Instance.CustomReports);
        break;
    case "HistoricalReportsContainer":
        AddReportItems(SessionRepository.Instance.HistoricalReports);
        break;
}

private void AddReportItems(IEnumerable<IReport> reports)
{
    foreach (var report in reports)
    {
        var reportItem = new RadListBoxItem(report.Name, report.ID.ToString());
        if (!Items.Any(item => int.Equals(item.Value, reportItem.Value)))
        {
            Items.Add(reportItem);
        }
    }
}

修改

在回答您的其他问题时,GetAllCustomReports是否可以返回实现IReport接口的类型?这将消除通过Select(report => new { report.Name, report.ID} )投射到匿名类型的需要,并且应该解决剩余的问题。

答案 1 :(得分:2)

如果项目共享一个接口或基本类型(或者你可以更改它们) - 那么你就可以根据该类型表达LINQ查询。

如果没有,如果您使用的是C#4,则可以将其键入dynamic,因为它们共享相同的属性。

答案 2 :(得分:0)

如果您正在寻找相同的两个属性并且它们具有相同的名称,那么您可能有一个很好的小型界面候选者?