关于Linq的select new查询语句用法的疑问
现有一段要被查询到的xml,局部如下:
- XML code
- <dsobject handle="Document-1480477" classname="Document" baseClassname="Document">- <props> <prop name="DocumentTypeDesc" type="10">Herry-jack</prop> </props></dsobject>
Linq查询如下:
- C# code
var query = from dsobject in document.Descendants("dsobject") where dsobject.Attribute("classname").Value == "Document" select new { DocID = new { Id = dsobject.Attribute("handle").Value, }, DocumentTypeDesc = from prop in dsobject.Descendants("prop") where prop.Attribute("name").Value == "DocumentTypeDesc" select new { Val = prop.Value } }//-----------------------------------------------string docid = item.DocID.Id;string dt = item.DocumentTypeDesc.First().Val;//-----------------------------------------------
现在的问题是:DocID = new{......},是什么作用?DocID只是一个要查询的字段而已吧,能在此对象做什么操作吗?DocumentTypeDesc =......也是这个疑问。
[解决办法]
定义一个匿名对象,这个对象就是DocID
new
{
Id = dsobject.Attribute("handle").Value,
}
DocID 包含了handle属性的值
后面也一样
[解决办法]
- C# code
//原代码写的有点画蛇添足了,简单写成这样就可以var query = from dsobject in document.Descendants("dsobject") where dsobject.Attribute("classname").Value == "Document" select new { Id = dsobject.Attribute("handle").Value, }, DocumentTypeDesc = from prop in dsobject.Descendants("prop") where prop.Attribute("name").Value == "DocumentTypeDesc" select prop.Value }