LINQ操作说明

一:LINQ的使用,查询表达式
    class Program
    {
        static void ReflectOverQueryResults(object resultSet)
        {
            Console.WriteLine("***** Info about your query *****");
            Console.WriteLine("resultSet is of type: {0}", resultSet.GetType().Name);
            Console.WriteLine("resultSet location: {0}", resultSet.GetType().Assembly);
        }
        static void QueryOverStrings()
        {
            string[] currentVideoGames = {"Morrowind",
                                                 "BioShock",
                                                 "Half Life 2: Episode 1",
                                                 "The Darkness", "Daxter",
                                                 "System Shock 2"};

            //from, in, where, orderby, and select LINQ query operators.
            IEnumerable<string> subset = from g in currentVideoGames
                                         where g.Length > 6
                                         orderby g
                                         select g;
            foreach (string s in subset)
                Console.WriteLine("Item: {0}", s);

            ReflectOverQueryResults(subset);
        }
        static void QueryOverInts()
        {
            int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8};

            var subset = from i in numbers where i < 10 select i;

            foreach (var i in subset)
                Console.WriteLine("Item: {0} ", i);

            ReflectOverQueryResults(subset);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with LINQ *****/n");
            QueryOverStrings();
            Console.ReadLine();

            QueryOverInts();

        }
    }

二:The Role of Differed Execution
    static void QueryOverInts()
    {
        int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };

        //IEnumerable<int> subset = from i in numbers where i < 10 select i;
        var subset = from i in numbers where i < 10 select i;
        //System.Collections.IEnumerable subset = from i in numbers where i < 10 select i;

        foreach (var i in subset)
            Console.WriteLine("Item: {0} ", i);
        //1,2,3,8

        numbers[0] = 4;//The Role of Differed Execution
        foreach (var j in subset)
            Console.WriteLine("{0} < 10", j);
        //4,1,2,3,8

        ReflectOverQueryResults(subset);
    }

三:The Role of Immediate Execution
    static void ImmediateExecution()
    {
        int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };

        int[] subsetAsIntArray = (from i in numbers where i < 10 select i).ToArray<int>();
        foreach (var i in subsetAsIntArray)
            Console.WriteLine("Item: {0} ", i);

        List<int> subsetAsListOfInts = (from i in numbers where i < 10 select i).ToList<int>();
        foreach (var i in subsetAsListOfInts)
            Console.WriteLine("Item: {0} ", i);
    }

四:基于类的LINQ,以及过滤功能(Filtering Data Using OfType<T>())
    class Program
    {
        class Car
        {
            public string PetName = string.Empty;
            public string Color = string.Empty;
            public int Speed;
            public string Make = string.Empty;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("***** More fun with LINQ Expressions *****/n");
 
            List<Car> myCars = new List<Car>()
            {
                new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
                new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
                new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"}
            };

            //var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c;
            //var fastCars = from c in myCars where c.Speed > 55 select c;

            IEnumerable<Car> myCarsEnum = myCars.OfType<Car>();//类似过滤功能
            var fastCars = from c in myCarsEnum where c.Speed > 55 select c;

            foreach (var car in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", car.PetName);
            }

            //过滤功能
            ArrayList myStuff = new ArrayList();
            myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" });
            IEnumerable<int> myInts = myStuff.OfType<int>();
            foreach (int i in myInts)
            {
                Console.WriteLine("Int value: {0}", i);
            }
        }
    }

五:The Internal Representation of LINQ Query Operators
    class Program
    {
        static void QueryStringWithOperators()
        {
            Console.WriteLine("***** Using Query Operators *****");
            string[] currentVideoGames = {"Morrowind",
                                             "BioShock",
                                             "Half Life 2: Episode 1",
                                             "The Darkness",
                                             "Daxter",
                                             "System Shock 2"};

            var subset = from g in currentVideoGames
                         where g.Length > 6
                         orderby g
                         select g;

            foreach (var s in subset)
                Console.WriteLine("Item: {0}", s);
        }

        static void QueryStringsWithEnumerableAndLambdas()
        {
            Console.WriteLine("***** Using Enumerable / Lambda Expressions *****");
            string[] currentVideoGames = {"Morrowind",
                                             "BioShock",
                                             "Half Life 2: Episode 1",
                                             "The Darkness",
                                             "Daxter",
                                             "System Shock 2"};

            var subset = currentVideoGames.
                Where(game => game.Length > 6).
                OrderBy(game => game).
                Select(game => game);

            foreach (var game in subset)
                Console.WriteLine("Item: {0}", game);
            Console.WriteLine();
        }

        static void QueryStringsWithAnonymousMethods()
        {
            Console.WriteLine("***** Using Anonymous Methods *****");
            string[] currentVideoGames = {"Morrowind",
                                             "BioShock",
                                             "Half Life 2: Episode 1",
                                             "The Darkness",
                                             "Daxter",
                                             "System Shock 2"};

            Func<string, bool> searchFilter = delegate(string game) { return game.Length > 6; };
            Func<string, string> itemToProcess = delegate(string s) { return s; };

            var subset = currentVideoGames.
                Where(searchFilter).
                OrderBy(itemToProcess).
                Select(itemToProcess);

            foreach (var game in subset)
                Console.WriteLine("Item: {0}", game);
        }

        public static void QueryStringsWithRawDelegates()
        {
            Console.WriteLine("***** Using Raw Delegates *****");

            // Assume we have an array of strings.
            string[] currentVideoGames = {"Morrowind",
                                             "BioShock",
                                             "Half Life 2: Episode 1",
                                             "The Darkness",
                                             "Daxter",
                                             "System Shock 2"};

            Func<string, bool> searchFilter = new Func<string, bool>(Filter);
            Func<string, string> itemToProcess = new Func<string, string>(ProcessItem);

            var subset = currentVideoGames.
                Where(searchFilter).
                OrderBy(itemToProcess).
                Select(itemToProcess);

            foreach (var game in subset)
                Console.WriteLine("Item: {0}", game);
            Console.WriteLine();
        }
        public static bool Filter(string s) { return s.Length > 6; }
        public static string ProcessItem(string s) { return s; }

        static void Main(string[] args)
        {
            QueryStringWithOperators();
            QueryStringsWithEnumerableAndLambdas();
            QueryStringsWithAnonymousMethods();
            QueryStringsWithRawDelegates();
        }
    }

六:LINQ操作符
    class Program
    {
        //from, in: Used to define the backbone for any LINQ expression, which allows you to extract a subset of data from a fitting container.
        //where: Used to define a restriction for which items to extract from a container.
        //select: Used to select a sequence from the container.
        //join, on, equals, into: Performs joins based on specified key. Remember, these “joins”do not need to have anything to do with data in a relational database.
        //orderby, ascending, descending: Allows the resulting subset to be ordered in ascending or descending order.
        //var l1 = from temp in ls
        //group temp by temp.Value into gp
        //select gp;
        //group, by: Yields a subset with data grouped by a specified value.

        //These generic methods can be called to transforma result set in various manners (Reverse<>(), ToArray<>(), ToList<>(), etc.).
        //Some are used to extract singletons from a result set, others perform various set operations (Distinct<>(), Union<>(), Intersect<>(), etc.),
        //still others aggregate results (Count<>(), Sum<>(), Min<>(), Max<>(), etc.).
        static void GetCount()
        {
            string[] currentVideoGames = {"Morrowind", "BioShock",
                "Half Life 2: Episode 1", "The Darkness",
                "Daxter", "System Shock 2"};

            int numb = (from g in currentVideoGames
                        where g.Length > 6
                        orderby g
                        select g).Count<string>();

            Console.WriteLine("{0} items honor the LINQ query.", numb);
        }
        static void ReversedSelection(Car[] myCars)
        {
            var subset = (from c in myCars select c).Reverse<Car>();

            var subset = from c in myCars select c;
            foreach (Car c in subset.Reverse<Car>())
            {
                Console.WriteLine(c.ToString());
            }
        }
        static void DistinctSelection(Car[] myCars)
        {
            var makes = (from c in myCars select c.Make).Distinct<string>();

            var makes = from c in myCars select c.Make;
            foreach (var m in makes.Distinct<string>())
            {
                Console.WriteLine("Make: {0}", m);
            }
        }
        static void NewSelection(Car[] myCars)
        {
            var makesColors = from c in myCars select new { c.Make, c.Color };
            foreach (var o in makesColors)
            {
                // Could also use Make and Color properties directly.
                Console.WriteLine(o.ToString());
            }
        }
        static void OrderedResults(Car[] myCars)
        {

            var subset = from c in myCars orderby c.PetName select c;
            Console.WriteLine("Ordered by PetName:");
            foreach (Car c in subset)
            {
                Console.WriteLine(c.ToString());
            }

            subset = from c in myCars
                     where c.Speed > 55
                     orderby c.PetName descending
                     select c;
            Console.WriteLine("/nCars going faster than 55, ordered by PetName:");
            foreach (Car c in subset)
            {
                Console.WriteLine(c.ToString());
            }
        }

        static void GetDiff()
        {
            List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
            List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
            var carDiff = (from c in myCars select c).Except(from c2 in yourCars select c2);
            Console.WriteLine("Here is what you don't have, but I do:");
            foreach (string s in carDiff)
                Console.WriteLine(s); // Prints Yugo.
        }
        static void Main(string[] args)
        {

        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值