我正在尝试在ID列上加入两个列表(flist和slist)。列表定义,类定义,列表内容和所需结果显示如下。
List<first> flist= new List<first>();
List<second> slist= new List<second>();
public class first
{
public string name { get; set; }
public int ID{ get; set; }
public string itemAttr { get; set; }
}
public class second
{
public int ID{ get; set; }
public string itemAttr{ get; set; }
}
列出内容
flist:
apples | 1
bananas| 2
trees | 3
slist:
1 | fruit
3 | not-fruit
期望的结果:
flist:
apples | 1 | fruit
bananas | 2 |
trees | 3 | not-fruit
答案 0 :(得分:10)
List<first> flist= new List<first>();
List<second> slist= new List<second>();
var result = from f in flist
join s in slist on f.ID equals s.ID into g
select new {
f.name,
f.ID,
itemAttr = g.Any() ? g.First().itemAttr : null
};
答案 1 :(得分:2)
试试这个
foreach(var f in first)
{
foreach(var s in second)
{
if(f.ID == s.ID)
{
f.fAttr = item.itemAtrr;
}
}
}
答案 2 :(得分:0)
您可以使用Linq的“左外”联接:
var joined = from l1 in flist
join l2 in slist on l1.ID equals l2.ID into gj
from l2_sub in gj.DefaultIfEmpty()
select new {
name = l1.name,
ID = l1.ID,
itemAttr = l2_sub == null ? String.Empty : l2_sub.itemAttr
};
答案 3 :(得分:0)
namespace WindowsFormsApplication26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<first> flist = new List<first>();
List<second> slist = new List<second>();
flist.Add(new first("apples", 1));
flist.Add(new first("bananas", 2));
flist.Add(new first("trees", 3));
slist.Add(new second(1, "Fruit"));
slist.Add(new second(2, ""));
slist.Add(new second(3, "Not-Fruit"));
var result = (from t in flist
join x in slist
on t.ID equals x.ID
select new
{
Name = t.name,
Id = t.ID,
attrib = x.itemAttr
}).ToList();
}
public class first
{
public first()
{
}
public first(string n, int id)
{
name = n;
ID = id;
}
public string name { get; set; }
public int ID { get; set; }
}
public class second
{
public second()
{
}
public second(int id, string itm)
{
ID = id;
itemAttr = itm;
}
public int ID { get; set; }
public string itemAttr { get; set; }
}
}
}
答案 4 :(得分:0)
有什么问题?使用参数创建一个新的第三个类:ID,name,itemAttr。使用此类创建新列表,并将在所需位置写入所需数据。