您的位置:首页 > 其它

在SharePoint 2010中使用Linq时候,请注意特殊字符

2011-03-20 10:28 399 查看
SharePoint 2010 增加了对LINQ的支持,增强了开发的能力。那么其中好事有一些晓得细节需要我们注意的。

例子:有一个自定义列表“Citys”, 其中包含一个”选项”类型的字段“GDP”,它包含如下的两个选项:





那么你有没有尝试过如何去使用LINQ获得这列的值,我们来看一下:

首先使用SPMetal工具生成实体类,我们在实体类中找到“GDP”这个字段:

internal enum GDP : int
{
None = 0,
Invalid = 1,
[Microsoft.SharePoint.Linq.ChoiceAttribute(Value = "5 per user/month")]
_5PerUserMonth = 2,
[Microsoft.SharePoint.Linq.ChoiceAttribute(Value = "10 per company/month")]
_10PerCompanyMonth = 4,
}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

如果这个时候,你直接使用

item.GDP.Value


来获得这列的值,那么你得到的肯定是“_5PerUserMonth” 或者 “_10PerCompanyMonth” , 而没有办法得到他真正的值。谁叫C#的变量命名规则不让使用“空格”或者“/”等呢。这个时候我们需要利用发射来获取到里面的值。

 

public void GetGDP()
{
var ctx =
new CityDataContext(WebUrl);
var cityList = from c in ctx.Citys
select c;
foreach (var item in cityList)
{
Console.WriteLine(stringValueOf(item.GDP));
}

}

public string stringValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
Microsoft.SharePoint.Linq.ChoiceAttribute[] attributes =
(Microsoft.SharePoint.Linq.ChoiceAttribute[])fi.GetCustomAttributes(
typeof(Microsoft.SharePoint.Linq.ChoiceAttribute),false);
if (attributes.Length > 0)
{
return attributes[0].Value;
}
else
{
return value.ToString();
}
}


如果列表中的其他列里面也存有这样的值,那么你使用的时候还真的要注意了。


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐