本文介绍了如何使用 linq 从父类和嵌套数组子类获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型来从数据库中获取数据:

I have the following model to get data from database:

    public class CultureResource
    {
        public string KeyName { get; set; }
        public List<Resource> Resources { get; set; }
    }

    public class Resource
    {
        public string Value { get; set; }
        public string Culture { get; set; }
    }

现在我的目标是获取列表 & 的数据culture 其中 keysCultureResource.KeyName 匹配 &cultureResource.Culture 匹配.如何在 IQueryable 上编写 linq 查询以获得 IList 的结果,其中 Result 可能如下所示:

Now my goal is to get data for a list of keys & culture where keys matches with CultureResource.KeyName & culture matches with Resource.Culture. How can I write a linq query on a IQueryable<CultureResource> to get a result of IList<Result> where Result may look like the following:

public class Result
{
    public string KeyName {get; set;}
    public string Value {get; set;}
}

我尝试了以下 Linq,但它抛出 $project 或 $group 不支持 {document}. 错误:

I have tried the following Linq, but it throws $project or $group does not support {document}. error:

public IDictionary<string, string> GetLocalizedValueList(string[] keys, string culture)
{
    // returns IQueryable<CultureResource>
    var cultureResources = _repository.GetItems<CultureResource>();     

    /***** This is the query *********/
    var query = from cr in cultureResources
              from r in cr.Resources
              where keys.Contains(cr.KeyName) && r.Culture == culture
              select new { cr.KeyName, r.Value };
              
    var result = query.ToList()
              
    //return some data
}

仅供参考:我的底层数据库是 mongo

FYI: my underlying database is mongo

推荐答案

这个怎么样

        var query = cultureResources.SelectMany(cultureResource => cultureResource.Resources.Select(resource => new { cultureResource.KeyName, resource.Value })).ToList();

这篇关于如何使用 linq 从父类和嵌套数组子类获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 05:49