【问题标题】:Concatenate<T>(List<T> list, string specifiedPropertyOfT)?Concatenate<T>(List<T> 列表,字符串指定PropertyOfT)?
【发布时间】:2011-12-16 15:10:58
【问题描述】:

从参数到属性?

public class ConcatenateListTMember
{
    public static void Test()
    {
        var someList = new List<AnyClass>();
        someList.Add(new AnyClass("value1"));
        someList.Add(new AnyClass("value2"));
        Console.WriteLine(Concatenate(someList, "SomeProperty"));
        Console.ReadLine();
    }

    static string Concatenate<T>(List<T> list, string specifiedPropertyOfT)
    {
        string output = String.Empty;
        // TODO: Somehow concatenate all the specified property elements in the list?
        return output;
    }
}

internal class AnyClass
{
    public AnyClass(string someProperty)
    {
        SomeProperty = someProperty;
    }

    public string SomeProperty { get; set; }
}

如何实现此代码示例中的泛型方法?

  • 请注意,如果可以使用其他类型实现相同的目标,specifiedPropertyOfT 不必是字符串。
  • 理想情况下,不需要反射:)

【问题讨论】:

    标签: c# linq generics reflection collections


    【解决方案1】:

    我认为您正在寻找 .NET 4 中 string.Join 的新重载,这将允许:

    IEnumerable<AnyClass> sequence = ...;
    string joined = string.Join(",", sequence.Select(x => x.SomeProperty));
    

    如果您不能使用 lambda 表达式来表达属性 - 例如因为这必须在执行时完成 - 那么您必须使用反射。

    请注意,Select 中的选择器不必返回字符串 - String.Join 将对任何非字符串值调用 ToString

    【讨论】:

      【解决方案2】:

      更好 - 一种扩展方法:

      static string Concatenate<T>(this IEnumerable<T> list, Func<T,string> func)
      {
          return String.Join("",list.Select(func));
      }
      

      用法:

      someList.Concatenate(i => i.SomeProperty);
      

      现场示例:http://rextester.com/runcode?code=LRA78268

      【讨论】:

        【解决方案3】:

        试试这样的。我在 IEnumerable 上创建了一个扩展方法:

        public static class Extension
        {
            public static string ConcatinateString<T>(this IEnumerable<T> collection, Func<T, string> GetValue)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in collection)
                {
                    sb.Append(GetValue(item));
                }
                return sb.ToString();
            }
        }
        

        那就这么称呼吧,你会使用这样的东西:

        var values = new List<TestClass>
                {
                    new TestClass(){Name="John",Comment="Hello"},
                    new TestClass(){Name="Smith", Comment="Word"}
                };
        string s = values.ConcatinateString((x => x.Name));
        string v = values.ConcatinateString((x => x.Comment));
        

        在此示例中为 s = "JohnSmith"v = "HelloWord"。 Func() 为您提供了灵活性。您基本上是在告诉函数去哪里获取要连接的字符串。我还使用了 StringBuilder 以防您使用长集合。

        【讨论】:

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