[英]Looking for LINQ expression for foreach loop
我有2個設備類,
public class Device1
{
public string DeviceName { get; set; }
public string IP { get; set; }
public bool IsExist { get; set; }
}
public class Device2
{
public string DeviceName { get; set; }
public string DeviceIP { get; set; }
}
對於“Device1 []”數組,“IsExist”的當前值為“false”,
private static Device1[] GetDevice1Arr()
{
List<Device1> d1List = new List<Device1>() {
new Device1 { DeviceName="d1", IP="1", IsExist=false},
new Device1 { DeviceName="d2", IP="1", IsExist=false}
};
return d1List.ToArray();
}
現在“Device2 []”數組沒有“IsExist”,
private static Device2[] GetDevice2Arr()
{
List<Device2> d2List = new List<Device2>() {
new Device2 { DeviceName="d1", DeviceIP="3"},
new Device2 { DeviceName="d2", DeviceIP="1"},
new Device2 { DeviceName="d2", DeviceIP="2"},
new Device2 { DeviceName="d3", DeviceIP="3"}
};
return d2List.ToArray();
}
現在我通過使用2“foreach”循環比較陣列“Device1 []”和“Device2 []”,如果DeviceName和DeviceIP相同,我重置“IsExist”=“true”。
在這里尋找LINQ替換或任何替代方式 。 謝謝!
Device1[] d1 = GetDevice1Arr();
Device2[] d2 = GetDevice2Arr();
foreach(var device1 in d1)
{
foreach(var device2 in d2)
{
if(device2.DeviceName == device1.DeviceName && device2.DeviceIP == device1.IP)
{
device1.IsExist = true;
}
}
}
您可以使用Linq替換內部 foreach
循環,但不能替換外部循環,因為Linq用於查詢不更新 。 你擁有的本質上是一個Any
查詢( d2
中的任何項目是否符合這個條件?):
Device1[] d1 = GetDevice1Arr();
Device2[] d2 = GetDevice2Arr();
foreach(var device1 in d1)
{
device1.IsExist = d2.Any(device2 =>
device2.DeviceName == device1.DeviceName
&& device2.DeviceIP == device1.IP));
}
可能有其他方法使用Intersect
, Join
, Where
等來查找需要更新的項目,但最后foreach
循環是更新它們的正確方法。
看起來你正在嘗試加入。 你可以在LINQ中做到這一點,但你仍然需要一個foreach
來更新結果的IsExist
:
var itemsToUpdate = from d1 in GetDevice1Arr()
join d2 in GetDevice2Arr()
on new { d1.DeviceName, d1.IP }
equals new { d2.DeviceName, IP = d2.DeviceIP }
select d1;
foreach(var d1 in itemsToUpdate)
d1.IsExist = true;
由於兩者都是列表(類型轉換為數組),因此可以使用List.ForEach迭代第一個列表,使用Any迭代內部列表。
d1.ForEach( d=> d.IsExist = d2.Any(x => x.DeviceIP == d.IP && x.DeviceName == d.DeviceName);
這個和所有其他解決方案使用兩個級別的迭代,並且只是現有解決方案的縮寫。 你無法擺脫它。
使用連接的另一個建議,但作為模擬的“左”連接獲得true或false:
Device1[] d1 = GetDevice1Arr();
Device2[] d2 = GetDevice2Arr();
foreach(var d in from dev1 in d1
join dd in d2 on new {dev1.DeviceName, dev1.IP} equals new {dd.DeviceName, IP = dd.DeviceIP} into d3
select new {dev1, Exists = d3.Any()})
d.dev1.IsExist= d.Exists;
d1.Where(x => d2.Any(y => x.IsExist = (x.DeviceName == y.DeviceName && x.IP == y.DeviceIP))).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.