【问题标题】:how to return a property based on another property condition using LINQ in .NET Core如何在 .NET Core 中使用 LINQ 根据另一个属性条件返回属性
【发布时间】:2021-08-04 18:47:38
【问题描述】:
{
"value": [{
            "odata.type": "SP.User",
            "odata.id": "https://www.test.com/_api/Web/GetUserById(37)",
            "odata.editLink": "Web/GetUserById(37)",
            "Id": 37,
            "IsHiddenInUI": false,
            "LoginName": "i:0#.w|domain\\jos",
            "Title": "Mr joseph",
            "PrincipalType": 1,
            "Email": "joe@yopmail.com",
            "IsEmailAuthenticationGuestUser": false,
            "IsShareByEmailGuestUser": false,
            "IsSiteAdmin": false,
            "UserId": {
                "NameId": "s-1-5-21-2613750078-2161710047-3166685486-1473",
                "NameIdIssuer": "urn:office:idp:activedirectory"
            }
        }, {
            "odata.type": "SP.User",
            "odata.id": "https://www.test.com/_api/Web/GetUserById(90)",
            "odata.editLink": "Web/GetUserById(90)",
            "Id": 90,
            "IsHiddenInUI": false,
            "LoginName": "i:0#.w|domain\\pam",
            "Title": "anthony",
            "PrincipalType": 1,
            "Email": "anthony@yopmail.com",
            "IsEmailAuthenticationGuestUser": false,
            "IsShareByEmailGuestUser": false,
            "IsSiteAdmin": false,
            "UserId": {
                "NameId": "s-1-5-21-2613750078-2161710047-3166685486-1437",
                "NameIdIssuer": "urn:office:idp:activedirectory"
            }
        }
}

在反序列化此 JSON 后,我想根据 Id 获取标题,所以如果 Id = 37 我想返回一个包含 Mr Joseph 的字符串。是否可以使用 LINQ 做到这一点?提前感谢您的帮助...

我很想上这门课:

public class UsersInformationValue
    {
        [JsonProperty("odata.type")]
        public string Odata_Type { get; set; }

        [JsonProperty("odata.id")]
        public string Odata_Id { get; set; }

        [JsonProperty("odata.editlink")]
        public string Odata_EditLink { get; set; }
        public int Id { get; set; }
        public bool IsHiddenInUI { get; set; }
        public string LoginName { get; set; }
        public string Title { get; set; }
        public int PrincipalType { get; set; }
        public string Email { get; set; }
        public bool IsEmailAuthenticationGuestUser { get; set; }
        public bool IsShareByEmailGuestUser { get; set; }
        public bool IsSiteAdmin { get; set; }
        public UserIdDetails UserId { get; set; }
    }

【问题讨论】:

  • 你的反序列化代码是什么样的? (以及您要反序列化的任何类)
  • @ErikPhilips 我添加了要反序列化的类

标签: json linq .net-core


【解决方案1】:

您可以通过投影轻松做到这一点。

var title = values.Where(v => v.Id == 37).Select(v => v.Title).FirstOrDefault();

【讨论】:

  • 感谢您的解决方案
【解决方案2】:
var title = values.FirstOrDefault(v => v.Id == 37)?.Title;

【讨论】:

  • ?? (string)null; 是多余的,因为 ?.Title 实际上是相同的东西,可以删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多