C# Linq查询以筛选出列表列表,而不使用删除

C# Linq查询以筛选出列表列表,而不使用删除,c#,linq,C#,Linq,我还没有很好地掌握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 str

我还没有很好地掌握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=“en”


试试这个。。。希望它能帮助您(也修复了您的一些代码):

类实体
{
公共字符串id{get;set;}
公共字符串类别{get;set;}
公共IList信息{get;set;}
}
课程详情
{
公共字符串id{get;set;}
公共字符串名称{get;set;}
公共字符串区域设置{get;set;}
}
列表=新列表();
添加(新实体{id=“1”,catagory=“cat1”,info=newlist{newdetails{locale=“en”,name=“d1”},newdetails{locale=“fr”,name=“d2”}});
list.Add(new entity{id=“2”,catagory=“cat2”,info=new list{new details{locale=“en”,name=“d3”}};
var result=list.Where(xx=>xx.info.Any(yy=>yy.locale==”);

只有linq的解决方案是:

var result = list.Select(item => new entity
        {
            id = item.id,
            catagory = item.catagory,
            info = item.info.Where(inner => inner.locale == "en").ToList()
        });
如果不想投射新的
条目
详细信息,则使用
foreach
循环,并在循环中为每个项目仅保留匹配的
详细信息

foreach (var item in list)
{
    item.info = item.info.Where(inner => inner.locale == "en").ToList();
}

请注意,您的类不遵循C#的命名约定:


@mohd-很高兴这对您有所帮助,感谢您将问题标记为已解决:)
 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 == ""));
var result = list.Select(item => new entity
        {
            id = item.id,
            catagory = item.catagory,
            info = item.info.Where(inner => inner.locale == "en").ToList()
        });
foreach (var item in list)
{
    item.info = item.info.Where(inner => inner.locale == "en").ToList();
}