c#中的字符串操作问题

时间:2013-01-29 13:58:47

标签: c# string

我在c#中遇到字符串操作问题。请检查以下表达式:

public static string UNID =  ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value.Substring( //issue is here

我想指出substring函数中的值,以便在其上应用indexOf函数。我尝试了this关键字但没有工作:

public static string UNID =  ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value.Substring(this.IndexOf('/') + 1);

我知道我们可以通过将表达式分解为以下部分来做同样的事情:

var value = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value;

var UNID = value.Substring(value.IndexOf('/') + 1);

但是,如果有任何解决方案,就像我尝试使用this关键字一样。那请告诉我?

2 个答案:

答案 0 :(得分:4)

就我个人而言,我认为将它作为两个单独的行是最好的方法,但如果你在一行上设置了死,你可以使用Split代替。第二个参数表示您只想拆分第一个分隔符。

var UNID = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
    .Claims.Single(c => c.ClaimType.Contains("nameidentifier"))
    .Value.Split(new[] {'/'}, 2)[1];

答案 1 :(得分:3)

这应该有效:

public static string UNID =  ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity).Claims
  .Where(c => c.ClaimType.Contains("nameidentifier"))
  .Select(c => c.Value.Substring(c.Value.IndexOf('/')+1))
  .Single();
  • 首先选择所请求的声明类型
  • 然后将其转换为正确的value-substring
  • 并采用唯一(预期)值