[英]Filter of two lists for the same elements via LINQ query in C#
我有一个要听的活动。 当设备设置发生变化时触发此事件。 然后,此事件为我提供了所有可用设备的列表。
现在我有所谓的站,每个站都链接到一个设备。 我发送一个返回所有这些电台的查询。
这两个字段都拥有一个DeviceUid
属性。 现在我想为每个设备执行某个 function,在站内也可以找到(见代码片段):
事件:
public class DeviceEvent
{
public virtual List<DeviceInfo> Device { get; set; }
}
我的方法:
public void SomeMethod(DeviceEvent evt)
{
var stations = Do.Query(new GetStationQuery(){ SomeInput })
.Where(x => x.DeviceIsRegistered)
.ToList();
// type: List<DeviceInfo>
var deviceInfoList = evt.Device;
// TODO: get DeviceInfo for each Device which can be found in stations.
foreach (var VARIABLE in COLLECTION)
{
DoSomething(station, deviceInfo);
}
}
private void DoSomething(StationInfo stationInfo,
DeviceInfo deviceInfo)
{
// some code
}
我的做法:
将stations
中相应的DeviceUid
存储为单独的列表 ( var stationDeviceUidList
)。 然后我检查是否可以在stationDeviceUidList
中找到来自deviceInfoList
的元素( Uid
)。
然后我用找到的Uids
获取所有DeviceInfo
,并将它们作为参数提供给DoSomething()
方法。
var stationDeviceUidList = stations.Select(x => x.DeviceId);
var deviceUidList = deviceInfoList.Select(x => x.DeviceUid)
.ToList();
// How do I get a corresponding Uid here?
var test = deviceUidList.Where(x => deviceUidList.Contains(stationDeviceUidList));
我无法正确完成最后一步,并且对 id 匹配的查询肯定是错误的。
我的方法是否有意义? 我希望你能帮助我并解释我的错误。
假设您的站 class 看起来像
class Station{
DeviceInfo Device = ...
int DeviceId = ... //or guid, doesn't matter
}
你的 DeviceInfo 看起来像:
class DeviceInfo{
int DeviceUid = ... //or guid, doesn't matter, this is equal to station.DeviceId
}
并且您的 DeviceInfo 事件列表称为 Devices (类列表应该是复数)
你可以:
context.Stations.Where(s => Devices.Any(d => d.DeviceUid == s.DeviceId))
这意味着“对于所有工作站,仅给出(事件设备列表中的设备等于工作站的设备 ID 的任何项目)的工作站” - 即“仅给出 ID 在事件设备列表中的设备的那些工作站”身份证"
您似乎有一些方法可以生成一个电台列表,我在里面看不到,但我不建议您首先(在任何阶段)使用 ToList() 处理您的电台,因为这意味着您的客户端会下载每个电台。 如果您将其保留为可查询,则无需下载每个电台即可形成查询,因此只有您想要的电台才会下载
哦,您可以将其他条件叠加到您的位置中:
context.Stations.Where(s => s.IsRegistered && Devices.Any(d => d.DeviceUid == s.DeviceId))
这个功能应该可以解决问题。 由于两个答案的方法,我能够调整相应的 LINQ 命令。
在上面的查询中,查询注册设备的站点就足够了,因为每个站点只包含一个设备。
在foreach
循环中,我还可以使用Single()
并将此信息传递给新方法。
public void SomeMethod(DeviceEvent evt)
{
var stationsInfo = var stations = Do.Query(new GetStationQuery(){ SomeInput });
var stationsForDevice = stationsInfo.Where(info => info.DeviceIsRegistered);
foreach (var stationInfo in stationsForDevice)
{
var deviceInfo = evt.Device.Single(info => info.DeviceUid.Equals(stationInfo.DeviceId));
DoSomething(stationInfo, deviceInfo );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.