C# 使用 LINQ 从类中提取 DARA
本文关键字:提取 DARA 使用 LINQ | 更新日期: 2023-09-27 17:59:10
>我有两个类:
public class Profile
{
private List<Location> location = new List<Location>();
public int Current { get; set; }
public List<Location> Location { get; set; }
}
public class Location
{
public int id { get; set; }
public Single x { get; set; }
public Single y { get; set; }
public Single z { get; set; }
public float Distance { get; set; }
}
我所做的是用我从 XML 获得的数据填充这两个类:
这是 XML 结构:
<start>
<level Current="2">
<GPSSpots>
<GPSSpot id="1" x="78492.61" y="-80973.03" z="-4403.297" Distance="90"/>
<GPSSpot id="2" x="78323.57" y="-81994.98" z="-4385.707" Distance="55"/>
<GPSSpot id="3" x="78250.57" y="-81994.98" z="-4385.707" Distance="43"/>
</GPSSpots>
<Vendor id = "1" x="123456" y="456789" z="0234324"/>
<Banker id = "1" x="23432" y="3243243" z="5154445"/>
<Relocate>
<Teleporter id = "1" MapID="1122" x="324324" y="23432" z="23432432"/>
<Teleporter id = "2" MapID="4444" x="324324" y="23432" z="23432432"/>
<Teleporter id = "3" MapID="2222" x="324324" y="23432" z="23432432"/>
</Relocate>
</start>
还有我的XML解析器方法:
public static List<Profile> ParseXml() //Parsing all them GPSSpots from XML
{
List<Profile> result = new List<Profile>(); //first we have to empty the list in case spawn will be called more than once
result.Clear();
doc = XDocument.Load(Document);
result = (from n in doc.Descendants("level")
select new Profile()
{
Current = int.Parse(n.Attribute("Current").Value),
Location = (from l in n.Element("GPSSpots").Elements("GPSSpot")
select new Location()
{
id = int.Parse(l.Attribute("id").Value),
x = Single.Parse(l.Attribute("x").Value),
y = Single.Parse(l.Attribute("y").Value),
z = Single.Parse(l.Attribute("z").Value),
Distance = Single.Parse(l.Attribute("Distance").Value)
}).ToList()
}).ToList();
return result;
}
我现在想做的是:
我需要从"配置文件类"中获取最接近的数字(Current
值(到比方说数字 10。
示例 1 如果我有数字list 1,4,7,12,20
正确的结果应该是 7。
例 28 如果我有数字list 1,21,22,44
正确的结果应该是 1。
我使用以下代码管理了它:
var ProperLevel = GPSSpots.Where(s => s.Current < 10).Max(s => s.Current);
现在我有了,我将不得不从类Location
中获取相应的数据,例如:拉节点Current
我们从类Profile
获得的值,并且从Distance
最低的Location
中检索ID
。
示例:假设我们的 var ProperLevel
返回2
(就像在我们的 XML 中只有一个节点一样(。现在我们必须从类 Locations
中提取正确的节点(相应的 var ProperLevel
(。现在我们有了数据,我们根据最低Distance
和返回ID
对其进行排序。
所以基于我们的XML结果应该是:
Current level = 2
ID = 3
Distance = 43
您可以选择一些选项来获取具有特定属性值的最大值/最小值的对象:
如何使用 LINQ 选择具有最小或最大属性值的对象
可用的最短选项之一是使用 Aggregate()
:
var ProperLevel = GPSSpots.Where(s => s.Current < 10)
.Aggregate((c, d) => c.Current > d.Current ? c : d);
var loc = ProperLevel.Location
.Aggregate((c, d) => c.Distance < d.Distance ? c : d);
Console.WriteLine("Current level = {0}", ProperLevel.Current);
Console.WriteLine("ID = {0}", loc.id);
Console.WriteLine("Distance = {0}", loc.Distance);
var loc = ProperLevel.Locations.Min(l=>l.Distance);
loc.Id...
loc.Distance