如何在Linq中循环遍历.select语句中的所有元素 [英] How can I loop Through all the elements in .select statement in Linq
问题描述
我正在尝试打印书名,作者名"(某些书有一位以上的作者) 在Linq代码下面仅打印第一作者.如何打印与一本书相关的所有作者?
I am trying to Print "Title of the Book , AuthorNames " (Some Books have more than one author) Below Linq code is printing only first author. How can I print all the authors associated with a book?
List<string> books = docs.Descendants(name)
.Select(x => new {
Title = (string)x.Element(ns+"TITLE"),
Author = x.Element(ns+"INTEL_AUTH")
})
.Select(x => new {
Title = x.Title,
FirstName = (string) x.Author.Element(ns+"FNAME"),
MiddleInitial = (string) x.Author.Element(ns+"MNAME"),
LastName = (string) x.Author.Element(ns+"LNAME"),
})
.Select(x => string.Format("{0}: {1} {2} {3}",
x.Title,
x.FirstName, x.MiddleInitial, x.LastName))
.ToList();
for (int i = 0; i < books.Count; i++)
{
Response.Write("--" + books[i] + "<BR />" );
}
XML 这是xml代码. 测试1 约翰 美国能源部 约翰 斯基特
XML Here is the xml code. TEST 1 JOHN DOE JOHN SKEET
<INTEL_AUTH ID="10">
<FNAME>JO</FNAME>
<MNAME></MNAME>
<LNAME>JO</LNAME>
<INTEL_AUTH>
</INTEL>
<INTEL>
<TILE> LEARNING LINQ</TITLE>
<INTEL_AUTH ID="2">
<FNAME> SHELLY</FNAME>
<MNAME></MNAME>
<LNAME>SHELLY</LNAME>
<INTEL_AUTH iD="3">
<FNAME>CHRIS</FNAME>
<MNAME></MNAME>
<LNAME>MADISON</LNAME>
</INTEL_AUTH>
</INTEL>
</RECORD>
</XML>
我希望显示输出,例如:(标题):所有写过该书的作者
I WANT THE OUTPUT TO BE DISPLAYED LIKE : (TITLE) : ALL AUTHORS WHO WROTE THAT BOOK
测试1:JOHN DOE,JOHN SKEET,JO JO 学习LINQ:SHELLY SHELLY,克里斯·麦迪森
TEST 1 : JOHN DOE , JOHN SKEET , JO JO LEARNING LINQ : SHELLY SHELLY , CHRIS MADISON
推荐答案
目前尚不清楚您是要一个具有多个作者的结果,还是要每个作者一个结果,还是希望在List<string>
.我怀疑这可以满足您的需求:
It's not clear whether you want a single result with multiple authors, or a single result per author, or how you'd expect this to be represented in a List<string>
. I suspect this will do what you need though:
var query = docs.Descendants(name)
// First get the relevant elements out of the main book element
.Select(x => new {
Title = (string) x.Element(ns + "TITLE"),
Authors = x.Elements(ns + "INTEL_AUTH")
})
// Now transform them from LINQ to XML into plain objects
.Select(x => new {
Title = x.Title,
Authors = x.Authors.Select(a => new {
FirstName = (string) a.Element(ns + "FNAME"),
MiddleInitial = (string) a.Element(ns + "MNAME"),
LastName = (string) a.Element(ns + "LNAME")
})
});
foreach (var book in query)
{
Console.WriteLine("{0}:", book.Title);
foreach (var author in book.Authors)
{
Console.WriteLine(" {0} {1} {2}",
author.FirstName, author.MiddleInitial,
author.LastName);
}
}
这篇关于如何在Linq中循环遍历.select语句中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!