搜索列表<entity>以获取具有类属性匹配值的记录?</entity>

时间:2014-10-08 16:00:10

标签: c# asp.net list search webforms

我在ASP.Net Forms应用程序中创建了一个名为Years_Of_Service的模型类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PROJECT.Models.Default
{
    public class Years_Of_Service
    {
        public int Year { get; set; }
        public string FiscalYear
        {
            get
            {
                return Year + "-" + (Year + 1);
            }
        }
        public decimal ServiceCredited { get; set; }
        public decimal Salary { get; set; }
        public string CoveredEmployer { get; set; }


        public string TotalService { get; set; }
        public string PurchasedorReinstatedService { get; set; }
    }
}

我成功查询了我的数据库,并通过我的自定义控件在此Model类中返回了适当的值,但是在某些特定情况下,我返回的记录具有相同的[Year]值:

Grid

我现在需要做的是循环浏览列表中的每个实体,如果2个或更多实体具有[Year]的匹配值,则将它们合并在一起并将[Covered Employer]的值更改为“Multiple Employers”

一个简单的foreach循环将引导我完成每个实体,但是我不知道如何对每个OTHER实体进行子搜索以获得匹配的[Year]值并合并2.可以任何人点我是否能够最好地完成这项任务?

这是我到目前为止的自定义控制页面代码:

public partial class YearsOfService : System.Web.UI.UserControl
{
    public List<Years_Of_Service> lyos { get; set; }
    public Years_Of_Service y_o_s { get; set; }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ApplyData();
        }
    }

    private void ApplyData()
    {

        foreach (Years_Of_Service yearsOfService in lyos)
        {
            // Search [lyos] for records with same [Year] value (ex. "2009-2010")
            // If found, Add the [Service] & [Salary] Values together under one [Year] record.
            // Change the newly "merged" record to say "Multiple Employers" for [CoveredEmployer]
        }

        salaryGridView.DataSource = lyos;
        salaryGridView.DataBind();

        if (y_o_s.TotalService.ToString() != null)
        {
            creditSalLabel.Text = y_o_s.TotalService.ToString();
        }
        else
        {
            creditSalLabel.Text = String.Empty;
        }

        if (y_o_s.PurchasedorReinstatedService.ToString() != null)
        {
            purchaseCreditLabel.Text = y_o_s.PurchasedorReinstatedService.ToString();
        }
        else
        {
            purchaseCreditLabel.Text = String.Empty;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您需要使用group by approach

应该是这样的:

var groupedByYearLyos = lyos.GroupBy(x => x.Year)
    .Select(x => new Years_Of_Service() 
        { 
            CoveredEmployer = x.Count() > 1 ? "Multiple Employers" : x.First().CoveredEmployer,
            Year = x.Key,
            Salary = x.Sum(y => y.Salary)
             //and etc 
        })
    .ToList();