欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LINQ简单使用与XML的转换

程序员文章站 2022-07-04 10:20:42
...

LINQ是什么?

LINQ(Language Integrated Query)语言集成查询是一组用于c#和Visual Basic语言的扩展。它允许编写C#或者Visual Basic代码以操作内存数据的方式,查询数据库。

 

LINQ怎么读?

lin-k    在这里Q不发q的音,而是发k的音,所以读做link。

 

使用LINQ进行不同的操作

查询、筛选并进行排序与分组的操作

var custQuery =

    from cust in customers

    group cust by cust.City into custGroup

    where custGroup.Count() > 2

    orderby custGroup.Key

    select custGroup;

联接操作

var innerJoinQuery =

    from cust in customers

    join dist in distributors on cust.City equals dist.City

    select new { CustomerName = cust.Name, DistributorName = dist.Name };

将内存中对象转换为XML

class XMLTransform

{

    static void Main()

    {           

        // Create the data source by using a collection initializer.

        // The Student class was defined previously in this topic.

        List<Student> students = new List<Student>()

        {

            new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores = new List<int>{97, 92, 81, 60}},

            new Student {First="Claire", Last="O’Donnell", ID=112, Scores = new List<int>{75, 84, 91, 39}},

            new Student {First="Sven", Last="Mortensen", ID=113, Scores = new List<int>{88, 94, 65, 91}},

        };



        // Create the query.

        var studentsToXML = new XElement("Root",

            from student in students

            let x = String.Format("{0},{1},{2},{3}", student.Scores[0],

                    student.Scores[1], student.Scores[2], student.Scores[3])

            select new XElement("student",

                       new XElement("First", student.First),

                       new XElement("Last", student.Last),

                       new XElement("Scores", x)

                    ) // end "student"

                ); // end "Root"



        // Execute the query.

        Console.WriteLine(studentsToXML);



        // Keep the console open in debug mode.

        Console.WriteLine("Press any key to exit.");

        Console.ReadKey();

    }

}

然后生成的xml文件如下:

<Root> 

  <student> 

    <First>Svetlana</First> 

    <Last>Omelchenko</Last> 

    <Scores>97,92,81,60</Scores> 

  </student> 

  <student> 

    <First>Claire</First> 

    <Last>O'Donnell</Last> 

    <Scores>75,84,91,39</Scores> 

  </student> 

  <student> 

    <First>Sven</First> 

    <Last>Mortensen</Last> 

    <Scores>88,94,65,91</Scores> 

  </student> 

</Root>