【问题标题】:Filter an object containing multiple lists on a common field c#在公共字段上过滤包含多个列表的对象c#
【发布时间】:2017-01-31 19:32:15
【问题描述】:

我正在尝试查找是否有一些快速方法来过滤在公共字段上具有多个列表元素的对象。例如,如果我在重要类中有重要身高和体重列表,我想过滤重要对象以返回由EntryDate 过滤的列表中的数据。

public class VitalHeight
{
  public int Id { get; set; }
  public string Value { get; set; }
  public string EnterDate { get; set; }
}

public class VitalWeight
{
  public int Id { get; set; }
  public string Value { get; set; }
  public string EnterDate { get; set; }
}

public class Vital
{
  public double PaientId { get; set; }
  public List<VitalWeight> Weights { get; set; }
  public List<VitalHeight> Heights { get; set; }
}

Vital vitals = controller.GetAllVitals(1234); // Get vitals by patient id

有没有一种简单的方法可以通过EntryDate 过滤我从GetAllVitals() 获得的生命体征?

我在vitals 对象中有类似的数据:

PatientId: 1234
Weights: {[Id: 1, Value: 290, EntryDate: 1/31/2017 12:34:00 PM], 
          [Id: 2, Value: 291, EntryDate: 1/31/2017 2:14:00 PM]}
Heights: {[Id: 1, Value: 5.7, EntryDate: 1/31/2017 12:34:00 PM]}

所以,EntryDate="1/31/2017 12:34:00 PM" 的输出应该是:

PatientId: 1234
Weights: {[Id: 1, Value: 290, EntryDate: 1/31/2017 12:34:00 PM]}
Heights: {[Id: 1, Value: 5.7, EntryDate: 1/31/2017 12:34:00 PM]}

生命体征中有更多具有相似结构的生命体征列表,我需要过滤EntryDate

我试图用 linq 来做这件事,但不太明白。

【问题讨论】:

  • 如果 VitalXxx 类具有相似的结构,为什么还要有多个类?您可以创建一个“通用”类并在不同的地方使用它。如果您不想这样做,我想抽象基类会很好。

标签: linq list c#-4.0


【解决方案1】:

为了澄清我的评论,这就是我使用“通用”重要类的意思:

public class GenericVital
{
  public int Id { get; set; }
  public string Value { get; set; }
  public string EnterDate { get; set; }
}

public class Vital
{
  public double PaientId { get; set; }
  public List<GenericVital> Weights { get; set; }
  public List<GenericVital> Heights { get; set; }
}

(我知道GenericVital 在这里可能是个坏名字。不过,我想你明白了。)

然后您可以通过以下方式获取生命体征:

var theDateYouAreLookingFor = DateTime.Now; // example date
var vitalsYouWant = vitals.Where(v => DateTime.Parse(v.EnterDate) == theDateYouAreLookingFor);

问题是,您无法区分重要信息是重要信息高度还是重要重量。如果您希望能够区分差异,您可以在类中添加一个属性,告诉您这是什么类型(不推荐)。

我认为“更好”的解决方案是引入这样的抽象基类:

public abstract class VitalBase
{
  public int Id { get; set; }
  public string Value { get; set; }
  public string EnterDate { get; set; }
}

public class VitalHeight : VitalBase
{
}

public class VitalWeight : VitalBase
{
}

public class Vital
{
  public double PaientId { get; set; }
  public List<VitalWeight> Weights { get; set; }
  public List<VitalHeight> Heights { get; set; }
}

您可以像已经显示的那样从GetAllVitals() 中过滤您的List&lt;VitalBase&gt;,并且可以通过反射获得类型。

另一种可能性是使用dynamic。但是,我认为这将是矫枉过正。

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2016-10-27
    • 1970-01-01
    • 2018-05-15
    • 2015-01-06
    • 1970-01-01
    相关资源
    最近更新 更多