如何将以下代码转换为LINQ格式?

时间:2014-02-18 11:30:19

标签: .net performance linq c#-4.0 foreach

代码:

foreach (var testType in projectData.TestTypes.OrderBy(it => it.TestName))
{
     var testList = new TestList
     {
          benchTestTypeName = testType.TestName,
          DataProvider = this.projectDataService.CurrentDataProvider,
          ProjectData = projectData
     };
     this.tabItems.Add(new TabItem { Header = testType.TestName, Content = testList });
}

如何将上述代码转换为LINQ格式?如果我们转换为Linq,执行时间(i.e)是否会有一点改进,执行时间是否可以减少一点?截至目前,15 TestTypes需要大约4到5秒。

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

var items = projectData.TestTypes
                       .OrderBy(it => it.TestName)
                       .Select(testType=> new TestList
                       {
                           benchTestTypeName = testType.TestName,
                           DataProvider = this.projectDataService.CurrentDataProvider,
                           ProjectData = projectData
                       });

foreach(var item in items)
   tabItems.Add(new TabItem { Header = item.benchTestTypeName, Content = item });