Linq join 3 list <T>
本文关键字:gt join lt list Linq | 更新日期: 2023-09-27 18:02:48
我有三个列表需要连接在一起
class Person
{
public int PersonID{ get; set; }
public string FirstName{get; set;}
public string LastName {get; set;}
}
class Traffic
{
public DateTime Date{ get; set; }
public int PersonID;
public int TrafficID;
}
class TrafficType
{
public int TrafficID { get; set; }
public string Description { get; set; }
}
List<Person> Persons=GetPersons();
List<TrafficType> TrafficTypes=GetTrafficTypes();
List<Traffic> Traffics=GetTraffics();
我需要这样的输出:
<>之前PersonID FirstName LastName Date描述大卫……2011/07/19样品描述from person in Persons
from traffic in traffics
from trafficType in trafficTypes
where trafficType.TrafficID = traffic.TrafficID
where traffic.PersonID = person.PersonID
select new
{
PersonID = person.PersonID,
....
}
var result = Persons.Join(
Traffics,
person => person.PersonID,
trafic => trafic.PersonID,
(person, trafic) => new
{
PersonId = person.PersonID,
FirstName = person.FirstName,
LastName = person.LastName,
Date = trafic.Date,
TraficId = trafic.TrafficID
}).Join(
TrafficTypes,
a => a.TraficId,
traficType => traficType.TrafficID,
(a, traficType) => new
{
PersonId = a.PersonId,
FirstName = a.FirstName,
LastName = a.LastName,
Date = a.Date,
Description = traficType.Description
});
下面是一个完整的Linq查询表达式代码示例,它应该得到你正在寻找的东西:
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Traffic
{
public DateTime Date { get; set; }
public int PersonId { get; set; }
public int TrafficId { get; set; }
}
class TrafficType
{
public int Id { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
var persons = new List<Person>()
{
new Person()
{
Id = 1001,
FirstName = "David",
LastName = "Jones",
},
};
var trafficTypes = new List<TrafficType>()
{
new TrafficType()
{
Id = 456,
Description = "sample description",
},
};
var traffics = new List<Traffic>()
{
new Traffic()
{
PersonId = 1001,
TrafficId = 456,
Date = DateTime.Now,
},
};
var joinedData = from p in persons
from t in traffics
from tt in trafficTypes
where p.Id == t.PersonId
&& tt.Id == t.TrafficId
select new
{
PersonId = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
// Remove time component, if present
Date = t.Date.Date,
Description = tt.Description,
};
foreach (var item in joinedData)
{
Console.WriteLine("{0}'t{1}'t{2}'t{3}'t{4}"
, item.PersonId
, item.FirstName
, item.LastName
, item.Date.ToShortDateString() // Don't print the time
, item.Description
);
}
}
}
程序输出为:
1001 David Jones 7/19/2011 sample description
你可以把它们都放在一个类中,例如(Problem),然后使用一个方法输出。
class Problem
{
public Problem()
{
}
public void Show()
{
// implement your output here
}
}
或者,如果你正在使用Windows窗体应用程序和感兴趣的表,你可以使用DataGridView控件。更多信息,请访问http://msdn.microsoft.com/en-us/library/e0ywh3cz.aspx
或者使用DataGrid: http://www.codeproject.com/KB/grid/usingdatagrid.aspx