执行Group By时的对象类型转换

时间:2013-08-06 15:49:08

标签: c# linq

我有一个清单。我需要通过应用Group By找到唯一的ExistingData记录。以下代码有效。

 var distinctItemsWorking = myCostPages
        .GroupBy(x => new { 
                             x.CostPageContent.Program, 
                             x.CostPageContent.Group, 
                             x.CostPageContent.Sequence })
        .Select(y => y.First());

现在我需要将唯一列表转换为List。我们在进行分组时如何实现这种转换?

C#方法

    public List<CostPage> GetCostPages(SearchEntity search, int pageIndex, int pageSize)
    {
        List<ExistingData> AllData = GetExistingData();

        var allMatchingValues = from existingDatas in AllData
                                where existingDatas.CostPageContent.Program == search.Program
                                select existingDatas;


        var query = allMatchingValues;
        List<ExistingData> currentSelectionForExistingData = query
            .Skip(pageIndex * pageSize)
            .Take(pageSize)
            .ToList();


        //var distinctItems = currentSelectionForExistingData.GroupBy(x => new { x.CostPageContent.Program, x.CostPageContent.Group, x.CostPageContent.Sequence })
        //                    .Select(y => new CostPage()
        //                    {
        //                        CostPageContent = y.CostPageContent 
        //                    }
        //                    );

        var distinctItemsWorking = currentSelectionForExistingData.GroupBy(x => new { x.CostPageContent.Program, x.CostPageContent.Group, x.CostPageContent.Sequence })
                           .Select(y => y.First());

        List<CostPage> myCostPages = new List<CostPage>();
        foreach (ExistingData exist in distinctItemsWorking)
        {
            CostPage c = new CostPage();
            c.CostPageContent = exist.CostPageContent;
            myCostPages.Add(c);
        }

        return myCostPages;
    }

其他课程

public class ExistingData
{
    public CostPageNumberContent CostPageContent { get; set; }
    public string ItemID { get; set; }
}

public class CostPage
{
    public CostPageNumberContent CostPageContent { get; set; }
}


public class CostPageNumberContent
{
    public string Program { get; set; }
    public string Group { get; set; }
    public string Sequence { get; set; }
}

public class SearchEntity
{
    public string Program { get; set; }
    public string Sequence { get; set; }
    public string ItemID { get; set; }
}

1 个答案:

答案 0 :(得分:2)

如果您要替换foreach,可以执行以下操作:

var myCostPages = currentSelectionForExistingData
    .GroupBy(x => new { x.CostPageContent.Program, x.CostPageContent.Group, 
                        x.CostPageContent.Sequence })
    .Select(y => new CostPage { CostPageContent = y.First().CostPageContent })
    .ToList();

CostPage对象创建为GroupBy毫无意义。 Select是执行此转换的正确位置。