LINQ 查询条件能不能指定字段在某个集合中取值?

ltolll 2015-10-17 05:44:37
using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{

public class student
{
public int id{get;set;}
public string name{get;set;}
}

public static void Main()
{
List<student> aList = new List<student>(){
new student{id = 1,name = "s1"},
new student{id = 2,name = "s2"},
new student{id = 3,name = "s3"}
};

List<student> bList = new List<student>(){
new student{id = 2},
new student{id = 2},
new student{id = 3}
};
var cList = (from c in bList select c.id).Distinct();
foreach(var s in cList)
{
Console.WriteLine(s);
}
}
}

现在能去除bList 中的id重复项,
输出为
2
3
拉下来能不能用LINQ实现, 指定aList.id在cList取值得到集合为
2 S2
3 S3
...全文
400 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Poopaye 2015-10-18
  • 打赏
  • 举报
回复
引用 4 楼 ltolll 的回复:
foreach行出错: 错误 1 无法将类型“int”转换为“Test.Program.student”
 var cList = (from c in bList select c.id).Distinct();
            foreach (student s in cList.Select(x => aList.Where(y => y.id == x).FirstOrDefault()))
            {
                Console.WriteLine(s.id + " " + s.name);
            }
是这个意思
ajianchina 2015-10-18
  • 打赏
  • 举报
回复
你要呼叫谁,那可能要等明天了 你的类定义就存在问题,你定义成了嵌套类,先将student移到Test类外面去。 然后你剩下的问题,你的错误是在这儿: cList.Select(x => aList.Where(y => y.id == x).FirstOrDefault()); id跟x自己想各是什么东东。 好了,你全部删光吧,改成: var cList = aList.Where(i => bList.Any(j => j.id == i.id)); //或者 //var cList = aList.Join(bList, a => a.id, b => b.id, (a, b) => a).Distinct(); foreach (var s in cList) { Console.WriteLine(s.id + " " + s.name); }
ltolll 2015-10-18
  • 打赏
  • 举报
回复
@lishanquan

            var cList = (from c in bList select c.id).Distinct();
            cList.Select(x => aList.Where(y => y.id == x).FirstOrDefault());
            foreach (student s in cList)
            {
                Console.WriteLine(s.id + " " + s.name);
            }

foreach行出错: 错误 1 无法将类型“int”转换为“Test.Program.student”
  • 打赏
  • 举报
回复
alist.Where(i=>blist.Any(j=>j.Id==i.id))
Poopaye 2015-10-17
  • 打赏
  • 举报
回复
cList.Select(x=>
Poopaye 2015-10-17
  • 打赏
  • 举报
回复
cList.Select(x => aList.Where(y => y.id == x).FirstOrDefault());

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧