从对象集合列表中获取属性值

时间:2011-03-01 10:22:25

标签: c# linq

我想使用对象集合的属性之一从对象集合中获取value属性。

使用Linq将对 SupplierSettingsList

进行查询
public class SupplierSettings
{
    private string Key;
    private SupplierSettingsPropertyEnum property;
    private string Value;
}

List<SupplierSettings> SupplierSettingsList =new List<SupplierSettingsDto>();

SupplierSettingsList .Add
(new SupplierSettings{Key="1",property=SupplierSettingsPropertyEnum.Name,Value="Name"});

SupplierSettingsList .Add
(new SupplierSettings{Key="2",property=SupplierSettingsPropertyEnum.StartTime,Value="7PM"});

SupplierSettingsList .Add
(new SupplierSettings{Key="3",property=SupplierSettingsPropertyEnum.EndTime,Value="10PM"});

SupplierSettingsList .Add
(new SupplierSettings{Key="4",property=SupplierSettingsPropertyEnum.Interval,Value="45"});

4 个答案:

答案 0 :(得分:2)

您正在寻找以下内容

var SupplierSettingsVales = SupplierSettings.
Where(x=>x.property==SupplierSettingsPropertyEnum.Interval)
    .Select(x=>x.Value);

答案 1 :(得分:2)

它可以写成

var results = from o in SupplierSettingsList
              where o.property == SupplierSettingsPropertyEnum.Interval
              select o.Value;

您还可以在LINQ Query samples中找到C: drive C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033CSharpSamples.zip解压缩并构建项目,位于文件夹LinqSamples

答案 2 :(得分:0)

var value = SupplierSettings
  .Where(x=>x.property==SupplierSettingsPropertyEnum.Interval)
  .Select(x=>x.Value);
  .FirstOrDefault();

答案 3 :(得分:0)

这是你要做的事情:

var query =
    from ss in SupplierSettingsList
    where ss.property == SupplierSettingsPropertyEnum.Interval
    select ss.Value;

我对你的SupplierSettings有点怀疑,因为它似乎不是OOP的一个很好的例子。您可能更好地考虑对象设计而不是解决此查询。只是一个建议。