2

我有一个类型供应商,它有一个属性 SupplierId 和另一个属性 NearestLocation,它是一个类型 SupplierLocation,SupplierLocation 由属性 SupplierId 和 DistanceFromDevice

class Supplier
{
    public int SupplierId { get; set; }
    public SupplierLocation NearestLocation { get; set; }
}

class SupplierLocation
{
    public int SupplierId { get; set; }
    public decimal DistanceFromDevice { get; set; }
    public double Longitude { get; set; }
    public double Latitude {get; set;}
}

我有一个供应商可以拥有多个位置的所有供应商位置的列表。我还计算了每个位置的 DistanceFromDevice 属性。我有一个列表,其 ID 可以在 SupplierLocations 列表中找到。

我想使用 linq 将我的供应商通过 SupplierId 加入到 SupplierLocation 并使用具有该特定供应商的所有位置的最小 DistanceFromDevice 值的 Location 填充 Supplier 类的 NearestLocation 属性。

希望这是有道理的。这可以使用linq完成吗?

提前谢谢了。保罗

4

2 回答 2

1

那么,您想设置等于一的NearestLocation位置Supplier吗?SupplierIdList<SupplierLocation>

假设您有一个List<SupplierLocation>名为“Locations”并且“currentSupplier”是Supplier您要分配的 NearestLocation:

try
{

    var minForSupplier = Locations.Where(x => x.SupplierId == currentSupplier.SupplierId).Min(x => x.DistanceFromDevice);

    currentSupplier.NearestLocation = Locations.Where(x => x.SupplierId == currentSupplier.SupplierId && x.DistanceFromDevice == minForSupplier).Single();
}
catch(InvalidOperationException e)
{
    // There is more than one SupplierLocation
}
于 2013-04-25T19:22:49.370 回答
1

这是 LINQPad 中的一个工作示例

void Main()
{
    var suppliers = new List<Supplier> 
    {
        new Supplier() {SupplierId = 1},
        new Supplier() {SupplierId = 2},
        new Supplier() {SupplierId = 5}
    };      

    var locations = new List<SupplierLocation>
    {
        new SupplierLocation {SupplierId = 1, DistanceFromDevice = 10, Latitude = 1, Longitude = 2},
        new SupplierLocation {SupplierId = 1, DistanceFromDevice = 20, Latitude = 1, Longitude = 3},
        new SupplierLocation {SupplierId = 1, DistanceFromDevice = 30, Latitude = 1, Longitude = 4},
        new SupplierLocation {SupplierId = 1, DistanceFromDevice = 40, Latitude = 1, Longitude = 5},
        new SupplierLocation {SupplierId = 2, DistanceFromDevice = 10, Latitude = 2, Longitude = 2},
        new SupplierLocation {SupplierId = 2, DistanceFromDevice = 20, Latitude = 2, Longitude = 3},
        new SupplierLocation {SupplierId = 3, DistanceFromDevice = 10, Latitude = 3, Longitude = 2}
    };

    var result = from s in suppliers
        join l in locations on s.SupplierId equals l.SupplierId
        into grp
        where grp.Count() > 0
        select new Supplier() { SupplierId = s.SupplierId, NearestLocation = grp.OrderBy (g => g.DistanceFromDevice).First()};

    result.Dump();
}

class Supplier
{
    public int SupplierId { get; set; }
    public SupplierLocation NearestLocation{ get; set; }
}

class SupplierLocation
{ 
    public int SupplierId { get ;set; }
    public decimal DistanceFromDevice  { get; set; }
    public double Longitude { get; set; }
    public double Latitude {get; set;}  
}
于 2013-04-25T19:48:25.047 回答