首页 > 代码库 > Linq:First FirstOrDefault

Linq:First FirstOrDefault

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace TestConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var classify_list = new List<Alliance_FAQ_Classify>
            {
                new Alliance_FAQ_Classify{ClassifyID =1,ClassifyName ="酒店"},
                new Alliance_FAQ_Classify{ClassifyID =2,ClassifyName ="机票"},
                new Alliance_FAQ_Classify{ClassifyID =3,ClassifyName ="团购"},
                new Alliance_FAQ_Classify{ClassifyID =5,ClassifyName ="旅游"},
                new Alliance_FAQ_Classify{ClassifyID =8,ClassifyName ="Other"}
            };

            var info_list = new List<Alliance_FAQ_Info>
            {
                new Alliance_FAQ_Info{FAQID =1,ClassifyID =1},
                new Alliance_FAQ_Info{FAQID =2,ClassifyID =1},
                new Alliance_FAQ_Info{FAQID =3,ClassifyID =1},
                new Alliance_FAQ_Info{FAQID =4,ClassifyID =1},
                new Alliance_FAQ_Info{FAQID =5,ClassifyID =1},
                new Alliance_FAQ_Info{FAQID =6,ClassifyID =1},

                new Alliance_FAQ_Info{FAQID =7,ClassifyID =2},
                new Alliance_FAQ_Info{FAQID =8,ClassifyID =2},
                new Alliance_FAQ_Info{FAQID =9,ClassifyID =2},

                new Alliance_FAQ_Info{FAQID =10,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =11,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =12,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =13,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =14,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =15,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =16,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =17,ClassifyID =3},
                new Alliance_FAQ_Info{FAQID =18,ClassifyID =3},

                new Alliance_FAQ_Info{FAQID =19,ClassifyID =5},
                new Alliance_FAQ_Info{FAQID =22,ClassifyID =5}
            };

            Alliance_FAQ_Classify faq = classify_list.Where(x => x.ClassifyID == 50).First();
            Alliance_FAQ_Classify faq2 = classify_list.Where(x => x.ClassifyID == 50).FirstOrDefault();
            string str = classify_list.Where(x => x.ClassifyID == 50).FirstOrDefault().ClassifyName.ToString();
            Console.ReadLine();
        }
    }

    public class Alliance_FAQ_Info
    {
        public int FAQID { get; set; }

        public int ClassifyID { get; set; }
    }

    public class Alliance_FAQ_Classify
    {
        public int ClassifyID { get; set; }

        public string ClassifyName { get; set; }
    }
}

第一个faq报错

faq2为null

str报错

 

其实是很简单的东西,就是没有注意