c# - 在 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
解决方案
两个答案可以解决 Mong Zhu 和Ehsan Sajjad所说的问题
您只需要向我们展示您想要包含/显示的属性Continent
或Country
或者我的回答是如果你不想覆盖你的反射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));
推荐阅读
- django - AWS ec2 Nginx + Django 服务器在没有太多流量的情况下轻松达到 100% 的 CPU 利用率
- java - 如何使用 FilterInputStream 就地替换两个或多个占位符?
- reactjs - 为什么 React.memo 的 areEqual 参数没有被执行
- node.js - 如何将相同的请求重定向到快递上的另一台服务器?
- java - Spring Boot 是否创建 N 个线程来处理 N 个 API 请求?
- php - 如何从 3 个连接表中获取供应商名称
- java - 夸库斯大学
没有按照公认的方式工作? - tensorflow - 在 keras 中训练机器学习模型的 GPU 和 XLA_CPU 有什么区别?
- python - 将打印功能的输出重定向到文本并禁用它
- floating-point - 如何在Matlab中的浮点变量中删除不需要的零?