我在过滤嵌套在更大列表中的字符串列表时遇到问题。我尝试过这样的事情:myList.FindAll(d => d.activities.Any(i => i.type.Contains("read")));但似乎有人正在回归我有一个“UserData”结构,如图所示:public class UserData{ public int id; public List<UserActivity> activities;}public class UserActivity{ public string activity; public string type;}有f.ex。两种类型的活动(“读”和“写”)我想做的是过滤给定的内容,List<UserData> myList如图所示List<UserData> newList = new List<UserData>();foreach(UserData d in myList){ UserData newD = new UserData(); newD.id = d.id; newD.activities= d.activities.FindAll(i =>i.type.Contains("read")); if (newD.activities.Any()) newList.Add(newD);}有没有办法用 Linq 查询巧妙地做到这一点?我想要弄清楚的是一个简短而整洁的 Linq 查询来过滤我所描述的嵌套列表......我知道这可能是一个装饰问题,但它仍然让我很困扰。
3 回答
萧十郎
TA贡献1815条经验 获得超13个赞
var newList = (from userData in myList
let newActivities = userData.activities.Where(i => i.type.Contains("read"))
where newActivities.Any()
select new UserData { id = userData.id, activities = newActivities.ToList() }).ToList();
慕侠2389804
TA贡献1719条经验 获得超6个赞
我通过使用解决了这个问题:
newList = myList.Where(d => d.activities.Any(act => act.type.Contains("read"))) .Select(d => new UserData { id = d.id, activities = new List<UserActivity>( d.activities.FindAll(act => act.type.Contains("read")) ) }) .ToList();
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
尝试以下操作:
List<UserData> newList = myList.Select(x => new UserData() { id = x.id, activities = x.activities.Where(y => y.type.Contains("read")).ToList() }) .Where(x => x.activities.Count > 0) .ToList();
- 3 回答
- 0 关注
- 112 浏览
添加回答
举报
0/150
提交
取消