使用Linq基于子对象属性最小值进行选择和更新

时间:2013-04-25 18:36:34

标签: linq c#-4.0

我有一个Type Supplier,它有一个属性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属性。 我有一个List,其ID可以在SupplierLocations List中找到。

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

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

非常感谢提前。 保罗

2 个答案:

答案 0 :(得分:1)

那么,您想在NearestLocation上设置SupplierSupplierId等于List<SupplierLocation>中的{1}}吗?

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

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
}

答案 1 :(得分: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;}  
}