如何将 Firebase 字典转换为 C# 中的类

问题描述 投票:0回答:1

我正在从 Firebase 检索用户列表,但他们是以 KVP 的身份出现的。

{[FirstName, Eric]}
{[LastNae, EricLastName]}
{[Email, [email protected]]}
{[Phone, 12345]}

我需要将此 KVP 列表转换为名为 Person Class 的对象类型列表

Person
{
string FirstName {get; set;}
string LastName {get; set;}
string Email {get; set;}
string Phone {get; set;}
}

最快速有效的方法是什么:

c# firebase list google-cloud-firestore
1个回答
0
投票

不确定后端的其余部分是如何构建的,但您可以尝试使用 LINQ 为从 Firebase 获得的每个 KVP 创建一个新的 Person 对象。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}
public class FirebaseConverter
{
    public List<Person> ConvertToPersonList(List<KeyValuePair<string, string>> firebaseData)
    {
        return firebaseData
            .GroupBy(kv => kv.Key)
            .Select(group => new Person
            {
                FirstName = GetValueByKey(group, "FirstName"),
                LastName = GetValueByKey(group, "LastName"),
                Email = GetValueByKey(group, "Email"),
                Phone = GetValueByKey(group, "Phone"),
            })
            .ToList();
    }

    private string GetValueByKey(IEnumerable<KeyValuePair<string, string>> group, string key)
    {
        return group.FirstOrDefault(kv => kv.Key == key).Value;
    }
}

如果您不想使用 LINQ,则可以将所有 KVP 存储在列表中并迭代它们,然后将键值对映射到 Person 类的属性。我个人会选择 LINQ 实现,因为它使代码更清晰。

© www.soinside.com 2019 - 2024. All rights reserved.