C#Linq使用三元表达式过滤数据

本文关键字:三元 表达式 过滤 数据 C#Linq | 更新日期: 2023-09-27 18:24:17

我试图用startDateendDate过滤一些数据,用ternary expression过滤where clause和用Linq过滤,但我似乎无法正确处理逻辑。

我正在使用搜索一个搜索模型:

public ForecastSearchModel ForecastSearchModel { get; set; }
public class ForecastSearchModel
    {
        public ForecastSearchModel()
        {
            StartDate = DateTime.Parse("01/01/2007");
            EndDate = DateTime.Now.AddYears(3);
            Fed = DateTime.Now.AddYears(3);
        }
        public int? ProjectId { get; set; }
        public string Companies { get; set; }
        public string Clients { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime Fed { get; set; }
        public string Consultants { get; set; }
        public string Managers { get; set; }
        public string RateTypes { get; set; }
        public double? Rate { get; set; }
    }

我试图过滤的object是:

public IEnumerable<Dictionary<Project, IEnumerable<ProjectExtension>>> LightForecastData { get; set; }

我目前使用的逻辑是:

this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any(y => y.Any(z => z.StartDate >= ForecastSearchModel.StartDate))).ToList();

startDateEndDateProjectExtension的属性,我要做的是仅对具有与项目关联的ProjectExtensionsdictionaries应用筛选器。

在我当前的代码中,我只得到具有ProjectExtensions(Values)的Projects(Keys),并且我希望保留没有任何ProjectExtensions的Projects。

我尝试过使用:

this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any() ? x.Values.Any(y => y.Any(z => z.StartDate >= ForecastSearchModel.StartDate)) : true).ToList();

,我的逻辑是:

  • 如果有任何值,请过滤我的日期
  • 否则什么都不做

,但它返回相同的结果。

如有帮助将不胜感激,谢谢!

更新

ForecastViewModel:

public class ForecastViewModel
    {
        public ForecastSearchModel ForecastSearchModel { get; set; }
        public List<GetItemHistory_Result> PextItemHistory { get; set; }
        public List<GetItemHistory_Result> ProjectItemHistory { get; set; }
        public List<GetItemHistory_Result> ProjectConsultantItemHistory { get; set; }
        public IEnumerable<Dictionary<Project, IEnumerable<ProjectExtension>>> LightForecastData { get; set; }
        public DateTime? changeSetStartDate { get; set; }
        public DateTime? changeSetEndDate { get; set; }
        public void Filter()
        {
            if (this.ForecastSearchModel.ProjectId != null)
            {
                this.LightForecastData = this.LightForecastData.Where(x => x.Keys.Select(y => y.ProjectId.ToString()).ToList().Contains(ForecastSearchModel.ProjectId.ToString())).ToList();
            }
            if (!string.IsNullOrEmpty(this.ForecastSearchModel.Companies))
            {
                var companyIds = ForecastSearchModel.Companies.Split(',');
                this.LightForecastData = this.LightForecastData.Where(c => companyIds.Contains(c.Keys.Select(x=> x.CompanyId.ToString()).Single()));
            }
            if (!string.IsNullOrEmpty(this.ForecastSearchModel.Clients))
            {
                var clientIds = ForecastSearchModel.Clients.Split(',');
                this.LightForecastData = this.LightForecastData.Where(c => clientIds.Contains(c.Keys.Select(x => x.EntityId.ToString()).Single()));
            }
            this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any() ? x.Values.Any(y => y.Any(z => z.StartDate >= ForecastSearchModel.StartDate)) : true).ToList();
            //this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any(y => y.Any(z => z.StartDate >= ForecastSearchModel.StartDate))).ToList();
            //this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any(y => y.Any(z => (z is IPextWithEndDate ? (z as IPextWithEndDate).EndDate <= ForecastSearchModel.EndDate : true)))).ToList();
            this.LightForecastData = this.LightForecastData.Where(c => c.Keys.Select(x => x.ForecastEndDate).Single() <= ForecastSearchModel.Fed);
            if (!string.IsNullOrEmpty(this.ForecastSearchModel.Consultants))
            {
                var consultantIds = ForecastSearchModel.Consultants.Split(',');
                this.LightForecastData = this.LightForecastData.Where(c => c.Keys.Select(x => x.Project_Consultants).Single().Any(consultant => consultantIds.Contains(consultant.ConsultantId.ToString()))).ToList();
            }
            if (!string.IsNullOrEmpty(this.ForecastSearchModel.Managers))
            {
                var managerIds = ForecastSearchModel.Managers.Split(',');
                this.LightForecastData = this.LightForecastData.Where(c => managerIds.Contains(c.Keys.Select(x => x.ManagerId.ToString()).Single())).ToList();
            }
            if (!string.IsNullOrEmpty(this.ForecastSearchModel.RateTypes))
            {
                var rateTypeIds = ForecastSearchModel.RateTypes.Split(',');
                this.LightForecastData = this.LightForecastData.Where(x => x.Values.Any(y => y.Any(z =>  rateTypeIds.Contains(z.TypeOfRateId.ToString())))).ToList();
            }
            if (this.ForecastSearchModel.Rate != null)
            {
                this.LightForecastData = LightForecastData.Where(x=> x.Values.Any(y => y.Any(z => ((IProjectExtension)z).Rate == ForecastSearchModel.Rate))).ToList();
            }
        }
    }
    public class ForecastSearchModel
    {
        public ForecastSearchModel()
        {
            StartDate = DateTime.Parse("01/01/2007");
            EndDate = DateTime.Now.AddYears(3);
            Fed = DateTime.Now.AddYears(3);
        }
        public int? ProjectId { get; set; }
        public string Companies { get; set; }
        public string Clients { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime Fed { get; set; }
        public string Consultants { get; set; }
        public string Managers { get; set; }
        public string RateTypes { get; set; }
        public double? Rate { get; set; }
    }
}

项目定义:

public partial class Project
    {
        public Project()
        {
            this.Confidential = true;
            this.ProjectExtensions = new HashSet<ProjectExtension>();
            this.SendingProcess = new HashSet<SendingProcess>();
            this.ContactEmploymentDetails = new HashSet<ContactEmploymentDetails>();
            this.Changes = new HashSet<Change>();
            this.Project_Consultants = new HashSet<Project_Consultant>();
            this.SecondaryManagers = new HashSet<Employee>();
            this.ClientSatisfactionRate = new HashSet<ClientSatisfactionRate>();
            this.Needs = new HashSet<Need>();
        }
        public int ProjectId { get; set; }
        public string Title { get; set; }
        public int ManagerId { get; set; }
        public Nullable<int> EntityId { get; set; }
        public int CompanyId { get; set; }
        public System.DateTime CreatedDate { get; set; }
        public int ProjectTypeId { get; set; }
        public int CreatedById { get; set; }
        public string Description { get; set; }
        public Nullable<int> BusinessLineId { get; set; }
        public bool Confidential { get; set; }
        public Nullable<int> FinalClientId { get; set; }
        public System.DateTime ForecastEndDate { get; set; }
        public ProjectStatus StatusId { get; set; }
        public Nullable<int> FinancialDetailsId { get; set; }
        public Nullable<int> ContactNameOnInvoiceId { get; set; }
        public Nullable<double> TheoreticalMargin { get; set; }
        public Nullable<int> IntercoDetailsId { get; set; }
        public InvoiceFrequency InvoiceFrequencyId { get; set; }
        public Nullable<int> InternalClientId { get; set; }
        public Nullable<long> RoleId { get; set; }
        public Confidentiality ConfidentialityId { get; set; }
        public string InvoiceDescription { get; set; }
        public Nullable<int> CancellationReasonId { get; set; }
        public virtual Employee CreatedBy { get; set; }
        public virtual Employee Manager { get; set; }
        public virtual Client Entity { get; set; }
        public virtual Client FinalClient { get; set; }
        public virtual BusinessLine BusinessLine { get; set; }
        public virtual ICollection<ProjectExtension> ProjectExtensions { get; set; }
        public virtual EntityFinancialDetails EntityFinancialDetails { get; set; }
        public virtual ContactEmploymentDetails ContactNameOnInvoice { get; set; }
        public virtual ICollection<SendingProcess> SendingProcess { get; set; }
        public virtual ProjectType ProjectType { get; set; }
        public virtual IntercoDetails IntercoDetails { get; set; }
        public virtual ICollection<ContactEmploymentDetails> ContactEmploymentDetails { get; set; }
        public virtual Company Company { get; set; }
        public virtual Company InternalClient { get; set; }
        public virtual ICollection<Change> Changes { get; set; }
        public virtual ICollection<Project_Consultant> Project_Consultants { get; set; }
        public virtual ICollection<Employee> SecondaryManagers { get; set; }
        public virtual ICollection<ClientSatisfactionRate> ClientSatisfactionRate { get; set; }
        public virtual ICollection<Need> Needs { get; set; }
        public virtual CancellationReason CancellationReason { get; set; }
    }

ProjectExtension定义:

public partial class ProjectExtension
    {
        public ProjectExtension()
        {
            this.FreeOfChargeTime = new HashSet<FreeOfChargeTime>();
            this.Milestone = new HashSet<Milestone>();
            this.Components = new HashSet<Component>();
            this.Overtimes = new HashSet<Overtime>();
            this.OnCalls = new HashSet<OnCall>();
            this.Reviews = new HashSet<Review>();
        }
        public int ProjectExtensionId { get; set; }
        public int ProjectId { get; set; }
        public System.DateTime StartDate { get; set; }
        public string ProjectExtensionNumber { get; set; }
        public int TypeOfRateId { get; set; }
        public string RateCurrencyId { get; set; }
        public bool ProjectExtensionMandatory { get; set; }
        public ProjectExtensionStatus StatusId { get; set; }
        public Nullable<long> RoleId { get; set; }
        public double TotalInvoiced { get; set; }
        public Nullable<int> CandidateId { get; set; }
        public bool RegularizationOnReal { get; set; }
        public Nullable<BaseRegularization> BaseRegularizationId { get; set; }
        public Nullable<double> MaxBillableAmount { get; set; }
        public bool IsBillable { get; set; }
        public bool IsExpenseProofMandatory { get; set; }
        public virtual Project Project { get; set; }
        public virtual Currency RateCurrency { get; set; }
        public virtual ICollection<FreeOfChargeTime> FreeOfChargeTime { get; set; }
        public virtual ICollection<Milestone> Milestone { get; set; }
        public virtual Candidate Candidate { get; set; }
        public virtual ICollection<Component> Components { get; set; }
        public virtual ICollection<Overtime> Overtimes { get; set; }
        public virtual ICollection<OnCall> OnCalls { get; set; }
        public virtual ICollection<Review> Reviews { get; set; }
    }

操作结果:

public ActionResult ForecastView(ForecastSearchModel forecastSearchModel, DateTime? changeSetStartDate, DateTime? changeSetEndDate)
        {
            var dateOffset = DateTime.Today.DayOfWeek - DayOfWeek.Monday;
            var lastMonday = DateTime.Today.AddDays(-dateOffset);
            var nextSunday = lastMonday.AddDays(6);
            if (changeSetStartDate == null)
            {
                changeSetStartDate = lastMonday;
            }
            if (changeSetEndDate == null)
            {
                changeSetEndDate = nextSunday;
            }
            var pextItemHistory = Db.GetItemHistory("Project", "ProjectExtension", changeSetStartDate, changeSetEndDate.Value.AddDays(1)).ToList();
            var projectItemHistory = Db.GetItemHistory("Project", "Project", changeSetStartDate, changeSetEndDate.Value.AddDays(1)).ToList();
            var projectConsultantsItemHistory = Db.GetItemHistory("Project", "Project_Consultant", changeSetStartDate, changeSetEndDate.Value.AddDays(1)).ToList();
            var pextHistoryIds = pextItemHistory.Select(p => Int32.Parse(p.Value)).Distinct().ToList();
            var projectHistoryIds = projectItemHistory.Select(p => Int32.Parse(p.Value)).Distinct().ToList();
            var projectConsultantsIds =projectConsultantsItemHistory.Select(p => Int32.Parse(p.Value)).Distinct().ToList();
            var companyList = Db.Companies;
            var clientList = Db.Clients;
            var employeeList = Db.Employees;
            foreach (var item in projectItemHistory)
            {
                if (item.ColumnName == "CompanyId")
                {
                    item.OldValue =
                        companyList.Where(x => x.ID.ToString() == item.OldValue)
                            .Select(x => x.CompanyCodeName)
                            .Single();
                    item.NewValue = 
                        companyList.Where(x => x.ID.ToString() == item.NewValue)
                            .Select(x => x.CompanyCodeName)
                            .Single();
                }
                if (item.ColumnName == "EntityId")
                {
                    item.OldValue =
                        clientList.Where(x => x.EntityId.ToString() == item.OldValue)
                            .Select(x => x.Name)
                            .Single();
                    item.NewValue =
                        clientList.Where(x => x.EntityId.ToString() == item.NewValue)
                            .Select(x => x.Name)
                            .Single();
                }
                if (item.ColumnName == "ManagerId")
                {
                    item.OldValue =
                        employeeList.Where(x => x.EmployeeId.ToString() == item.OldValue)
                            .Select(x => x.Firstname + " " + x.Lastname)
                            .Single();
                    item.NewValue =
                        employeeList.Where(x => x.EmployeeId.ToString() == item.NewValue)
                            .Select(x => x.Firstname + " " + x.Lastname)
                            .Single();
                }
            }
            foreach (var item in projectConsultantsItemHistory)
            {
                if (item.ColumnName == "ConsultantId")
                {
                    item.OldValue =
                        employeeList.Where(x => x.EmployeeId.ToString() == item.OldValue)
                            .Select(x => x.Firstname + " " + x.Lastname)
                            .Single();
                    item.NewValue =
                        employeeList.Where(x => x.EmployeeId.ToString() == item.NewValue)
                            .Select(x => x.Firstname + " " + x.Lastname)
                            .Single();
                }
            }
            var data = Db.Projects.Where(
                x =>
                    projectHistoryIds.Contains(x.ProjectId) ||
                    x.Project_Consultants.Any(y => projectConsultantsIds.Contains(y.ProjectConsultantId)) ||
                    x.ProjectExtensions.Any(y => pextHistoryIds.Contains(y.ProjectExtensionId)))
                .WithTreeSecurity(LoggedEmployee.EmployeeId)
                .ToList()
                .Select(x =>  new Dictionary<Models.Project, IEnumerable<ProjectExtension>>()
                    {
                        {x, x.ProjectExtensions.Where(y => pextHistoryIds.Contains(y.ProjectExtensionId)).ToList()}
                })
                .ToList();
            var model = new ForecastViewModel { LightForecastData = data, ForecastSearchModel = forecastSearchModel, PextItemHistory = pextItemHistory, ProjectItemHistory = projectItemHistory , ProjectConsultantItemHistory = projectConsultantsItemHistory, changeSetStartDate = changeSetStartDate, changeSetEndDate = changeSetEndDate };
            model.Filter();
            return View("ForecastView", model);
        }

C#Linq使用三元表达式过滤数据

如果我理解正确,您希望保持相同的结构,只需要删除所有与筛选器不匹配的ProjectExtension对象。

试试这个:

var result = LightForecastData
    .Select(
    dic =>
        dic.Select(
            kvp =>
                new KeyValuePair<Project, IEnumerable<ProjectExtension>>(kvp.Key,
                    kvp.Value.Where(pe => pe.startDate >= ForecastSearchModel.StartDate).ToList()))
            .ToDictionary(x => x.Key, x => x.Value))
    .ToList();