从名称匹配的列表列中选择值

时间:2018-07-17 09:10:52

标签: c# list linq

我有一个包含不同列NameBitrate的列表。

public class VideoQuality
{
    public string Name { get; set; }
    public string Bitrate { get; set; }
}

public List<VideoQuality> quality = new List<VideoQuality>()
{
     new VideoQuality() { Name = "High",   Bitrate = "5000K" },
     new VideoQuality() { Name = "Medium", Bitrate = "2500K" },
     new VideoQuality() { Name = "Low",    Bitrate = "500K" },
};

如何从BitrateHigh的列表中选择?

类似的东西:

if (selectedQuality == "High")
{
    // Select High Bitrate from List
    string vBitrate = quality.Select(x => x.Bitrate)
                             .Where(Name = "High");
}

vBitrate应该等于5000K

2 个答案:

答案 0 :(得分:6)

您首先要过滤,然后选择:

var result = quality.Where(x => x.Name == "High")
                    .Select(x => x.Bitrate); //IEnumerable<string>

在查询语法中:

var result = from x in quality
             where x.Name == "High"
             select x.Bitrate; //IEnumerable<string>

请注意,无论如何IEnumerable<string>而不是单个项目的结果。如果您只想要一个项目,则使用FirstOrDefault / First / SingleSingleOrDefault

var result = quality.FirstOrDefault(x => x.Name == "High")?.Bitrate; //string

有关不同方法之间的差异,请参见文档和LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

答案 1 :(得分:3)

如果您希望最多返回一个 值,则建议使用FirstOrDefault

string vBitrate = quality
  .FirstOrDefault(item => item.Name == "High")
 ?.BitRate;