我还没有很好地掌握LINQ,感觉我的代码可以优化,以寻求帮助。 贝娄是我的模特
class entity
{
public string id { get; set; }
public string catagory { get; set; }
public IList<details> info{ get; set;}
}
class details
{
public string id{ get; set; }
public string name { get; set; }
public string locale { get; set; }
}
List<entity> list = new List<entity>();
list.Add(new entity { id = "1", catagory = "cat1", info = new { locale = "en", name = "d1" }, { locale = "fr", name = "d2" } });
list.Add(new entity { id = "2", catagory = "cat2", info = new { locale = "en", name = "d3" }});
需要根据区域设置过滤掉,假设我只需要获得locale =&#34; en&#34;列表..
为了清晰起见,在json中建模
{
"id": "1",
"catagory": "cat1",
"info": [{"locale":"en","name":"d1"},{"locale":"fr","name":"d1"}]
},
{
"id": "2",
"catagory": "cat2",
"info": [{"locale":"en","name":"d3"}]
}
预期结果 - 仅获取区域设置=&#34; en&#34;
{
"id": "1",
"catagory": "cat1",
"info": [{"locale":"en","name":"d1"}]
},
{
"id": "2",
"catagory": "cat2",
"info": [{"locale":"en","name":"d3"}]
}`
答案 0 :(得分:1)
仅限linq的解决方案将是:
var result = list.Select(item => new entity
{
id = item.id,
catagory = item.catagory,
info = item.info.Where(inner => inner.locale == "en").ToList()
});
如果您不想投射新的entry
个详细信息,请使用foreach
循环,并在其中为每个项目保留仅匹配的details
:
foreach (var item in list)
{
item.info = item.info.Where(inner => inner.locale == "en").ToList();
}
请注意,您的课程不遵循C#的命名惯例:
答案 1 :(得分:0)
试试这个...希望它可以帮助你(修复你的一些代码):
class entity
{
public string id { get; set; }
public string catagory { get; set; }
public IList<details> info { get; set; }
}
class details
{
public string id { get; set; }
public string name { get; set; }
public string locale { get; set; }
}
List<entity> list = new List<entity>();
list.Add(new entity { id = "1", catagory = "cat1", info = new List<details> { new details { locale = "en", name = "d1" }, new details { locale = "fr", name = "d2" } } });
list.Add(new entity { id = "2", catagory = "cat2", info = new List<details> { new details { locale = "en", name = "d3" } } });
var result = list.Where(xx => xx.info.Any(yy => yy.locale == ""));