[TestClass] public class XmlLinqTest { PRivate static XElement doc; [ClassInitialize] public static void Initialize(TestContext context) { doc = XElement.Load("Books.xml"); } [TestMethod] public void QueryBook_Id_ReturnBook() { IEnumerable<XElement> books=from el in doc.Elements() where el.Attribute("id").Value.Equals("1") select el; XElement book = books.First(); Assert.AreEqual(book.Attribute("id").Value, "1"); Assert.AreEqual(book.Attribute("name").Value,"Linq"); Assert.AreEqual(book.Attribute("author").Value,"Tom"); } }
<?xml version="1.0" encoding="utf-8" ?> <Books> <Book id="1" name="Linq" author="Tom" /> <Book id="2" name="Lambda" author="Jerry" /> </Books>
// custQuery 的类型是IEnumerable<IGrouping<string, Customer>>// IGrouping是group.. by语句的返回类型var custQuery = from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key select custGroup;
<?xml version="1.0" encoding="utf-8" ?><Authors> <Author id="1" name="Tom" /> <Author id="2" name="Jerry"/> <Author id="3" name="Jack"/></Authors><?xml version="1.0" encoding="utf-8" ?> <Books> <Book id="1" name="Linq" authorId="1" /> <Book id="2" name="Lambda" authorId="2" /> <Book id="3" name="C#" authorId="1" /></Books>//BooksGroup是Books xml中满足条件的element的集合
var group = from author in authors.Elements() join book in books.Elements() on author.Attribute("id").Value equals book.Attribute("authorId").Value into BooksGroup where author.Attribute("id").Value.Equals("1") select new { Author = author.Attribute("name").Value, authorBooks = BooksGroup };
int[] numbers = { 5, 10, 8, 3, 6, 12}; //Query syntax: IEnumerable<int> numQuery1 = from num in numbers where num % 2 == 0 orderby num select num; //Method syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);
新闻热点
疑难解答