获取类中变量的所有值

时间:2013-04-14 03:37:44

标签: c#

我有两个类,其中一个是Destinations,另一个是DestinationDetails

public class Destinations
{
    public Destinations() { }

    public string CarrierName { get; set; }

    public List<DestinationDetails> Details { get; set; }
}

public class DestinationDetails
{
    public DestinationDetails() { }

    public string Destination { get; set; }

    public string Type { get; set; }

}

我希望从第一个类的对象列表中获取第二个类中的所有string "Destination"

我有List<Destinations>,我不想使用for loop or foreach个陈述

3 个答案:

答案 0 :(得分:1)

var dest = new Destinations();

//Initialize the details

var destNames = dest.Details.Select(d => d.Destination).ToList();

答案 1 :(得分:1)

你在找这样的东西吗?

     var det = new Destinations();
     det.Details = new List<DestinationDetails>();
      det.Details.Add(new DestinationDetails() { Destination = "CA" });
      det.Details.Add(new DestinationDetails() { Destination = "NJ" });
      ...
      ...
     var details = new DestinationDetails();
     details.Destination = string.Join(",",det.Details.Select(x => x.Destination).ToArray() );

更新: -

提供目的地列表“allDet”,您可以获得如下字符串列表: -

  alldet.Where(x => x.Details != null).SelectMany(x => x.Details.Select(y => y.Destination)).ToList() //With out ToList() it will give you IEnumerable<String>

答案 2 :(得分:0)

List<Destinations> AirportDestinations ; //此列表包含DestinationsDetailsDestination

的对象

所以使用SelectMany

List<string> cities.AddRange(AirportDestinations.Where(x => x.Details != null).SelectMany(d => d.Details.Select(s => s.Destination)));

现在,列表中的所有对象都有Destination