【问题标题】:C# MVC2 - Generic Collection to IEnumerable<string>C# MVC2 - IEnumerable<string> 的通用集合
【发布时间】:2010-10-25 06:34:17
【问题描述】:

我似乎无法解决这个问题...请帮忙,谢谢你 vm!

我有一个通用的功能集合。每个功能都有一个 FeatureId 和 FeatureName。我需要将 featureids 传递给 IEnumerable&lt;string&gt;

我以为我很接近这个:

Listing.Features.ToArray().Cast<string>().AsEnumerable();

甚至尝试像“MacGyver”一样

 var sb = new System.Text.StringBuilder();

 foreach (Feature f in Listing.Features)
 {
     sb.AppendFormat("{0}", f.FeatureId);
 }          
 SelectedFeatures = sb.ToString().ToArray();

SelectedFeatures 是 IEnumerable&lt;string&gt;

我接近了吗?我更喜欢第一次尝试,因为它更干净,但现在我被卡住了,我不再挑剔了

【问题讨论】:

  • Listing.Features 对应的 type 是什么? List? IQueryable?

标签: c# .net generics


【解决方案1】:

如果我理解你需要的正确,像这样:

var selectedFeatures = Listing.Features.Select(item=>item.FeatureId);

item.FeatureName 视情况而定。上面的示例为您提供了IEnumerable&lt;T&gt;,其中T==Item.FeatureId.GetType();

【讨论】:

  • .AsEnumerable() 是多余的 - .Select 返回 IEnumerable
  • 我也对其进行了编辑以添加它!呵呵
  • 哇,你真快,我刚刚发布了我的附录……你说得对!泰!
  • 我在我的回答中错过了ToString()! :)
【解决方案2】:

我在另一个项目中发现了一个对我有帮助的旧代码示例……这就是我的工作方式:

Model.SelectedFeatures.Select(c => c.FeatureId.ToString())

还是谢谢你,HTH some1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多