首页 > 解决方案 > 在 join 语句中强制转换对象

问题描述

想要连接在我的 ListBox (SelectedItems) 中选择的所有项目。列表框使用类 (RegionModel) 作为数据源。

我在 foreach 循环中有这个,但如果可能的话,我想把它放在一行中。我所拥有的不会破坏,但不会打印,只是项目代表的类名。

namespace ProLimb.Models
{
    public class RegionModel
    {
        public string Continent { get; set; }
        public string Country { get; set; }
    }

    //TRYING TO GET TO WORK
    Regions = string.Join("; ", lstRegions.SelectedItems.OfType<object>());
}

我想我需要投射它,它似乎不起作用。

最终输出应如下所示:“North; East; South; West”,但结果却是:ProLimb.Forms.RegionModel

标签: c#linqcasting

解决方案


两个答案可以解决 Mong Zhu 和Ehsan Sajjad所说的问题

您只需要向我们展示您想要包含/显示的属性ContinentCountry

或者我的回答是如果你不想覆盖你的反射ToString()

PropertyYouWantToShow要么是Continent要么Country

Regions = string.Join("; ", lstRegions.SelectedItems.OfType<object>()
                .Select(c => c.GetType()
                              .GetProperty("PropertyYouWantToShow") //will get property
                              .GetValue(c))); //will get values listed on PropertyYouWantToShow

或者您可以select按照 Richard Barker的要求将其投射到您的帐户中,但仍然添加OfType<object>

Regions = string.Join("; ", lstRegions.SelectedItems.OfType<object>()
                .Select(c => ((RegionModel)c).PropertyYouWantToShow)); // either Country or Continent

或者您可以直接将其投射到您的OfType

Regions = string.Join("; ", lstRegions.SelectedItems.OfType<RegionModel>()
                .Select(c => c.PropertyYouWantToShow));

推荐阅读