C# 中的字符串操作问题

本文关键字:操作 问题 字符串 | 更新日期: 2023-09-27 17:56:25

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

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

我想指出子字符串函数中的值以在其上应用 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。那么请告诉我?

C# 中的字符串操作问题

我个人认为将其作为两行是最好的方法,但是如果您死在一行上,则可以改用Split。 第二个参数指示您只想在第一个分隔符上拆分。

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

这应该有效:

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();
  • 首先选择请求的声明类型
  • 然后将其转换为正确的值子字符串
  • 并取唯一的(预期)值