IEnumberable<String> To String

如何根据关键字在List<T>中查询出来相应的结果?

Code:

  • Create List<T>

        public class A {
            public string a { get; set; }
            public string b { get; set; }
        }

 

        List<A> aList = new List<A> {
            new A{ a="6", b="AAA"},
            new A{ a="2", b="BBB"}
        };

  • Search List<T>

      //这样是有问题的,无法隐式从IEnumerable<String>转换String

      String c = aList.Where ( o => o.a.Equals ( "6" ) )
                     .Select(o=>o.b);

image

   //这样是没有问题的,但是返回值不对,是当前类型名

     String c = aList.Where ( o => o.a.Equals ( "6" ) )
                      .Select(o=>o.b).ToString();

 

  • 那如何解决?

    使用FirstOrDefault()

    String c = aList.Where ( o => o.a.Equals ( "6" ) )
                            .FirstOrDefault ().b;

     OK了,但是好像有点问题,什么问题呢?

     如果这个集合没有我查询的值,肯定会报错的。

      String c = aList.Where ( o => o.a.Equals ( "1" ) )
                            .FirstOrDefault ().b;

image

  • 那又如何解决呢?

        有两种方案 

  • 编写自定义方法

  String d = Get ( aList , "1" );

        private string Get (List<A> aList , String whereStr) {
           var es = aList.Where ( o => o.a.Equals ( whereStr ) ).FirstOrDefault ();
           if ( es != null ) {
               return es.b;
           }
           else {
               return String.Empty;
           }
       }

或者

        Func<List<A> , String , String> Get = (list , str) => {
            var es = list.Where ( o => o.a.Equals ( str ) ).FirstOrDefault ();
            if ( es != null ) {
                return es.b;
            }
            else {
                return String.Empty;
            }
        };

       String ee = Get ( aList , "1" ); 

  • 编写扩展方法

            自行发挥!

posted @ 2010-03-22 17:43  RicoRui  阅读(2018)  评论(7编辑  收藏  举报