返回满足特定条件的列表元素

时间:2015-07-14 01:10:35

标签: c# linq

我有一个班级:

class Point
{
    double X, Y;
}

List<Point>开始,我想要Point列表中Point.X + Point.Y最多的地方 currentListView.kendoListView({ dataSource: vm.dataSource, template: kendo.template( ko.computed(function(){ return view() === 'full' ? firstTemplate : secondTemplate; }, this)), //code continue 。我如何在LINQ中执行此操作?

4 个答案:

答案 0 :(得分:6)

这将是一种方式(尽管不是最佳方式):

List<Point> list = ...;
Point maxPoint = list.OrderByDescending(p => p.X + p.Y).First();

另一种表现更好的方法是修改Point类以实现IComparable<T>,如下所示:

class Point : IComparable<Point>
{
    double X, Y;

    public int CompareTo(Point other)
    {
        return (X + Y).CompareTo(other.X + other.Y);
    }
}

...这将允许您简单地执行:

List<Point> list = ...;
Point maxPoint = list.Max();

答案 1 :(得分:2)

我会添加Microsoft Reactive Team的Interactive Extensions(NuGet&#34; Ix-Main&#34;)。他们有一堆非常有用的IEnumerable<T>扩展名。

这是你需要的:

Point max = points.MaxBy(p => p.X + p.Y).First();

答案 2 :(得分:0)

var maxValue = list.Max(m => m.X + m.Y);
var maxPoint = list.Where(p => p.X + p.Y == maxValue).FirstOrDefault();

为高地人..

var largestPoints = list.Where(p => p.X + p.Y == maxValue);

表示关系。

答案 3 :(得分:0)

没有任何开箱即用的东西。你可以这样做:

  var redeemnum = req.body.redeemnum;
  var country = Parse.Object.extend("country");  
  var query = new Parse.Query(country); 
  query.equalTo("name", redeemnum);
  query.first({  
   success: function(object) {
       if (typeof object === 'undefined') {
           res.render("wrong", { msg : "Failed!" } );
       } 
       else { 
            res.render("wrong", { msg : "Got it!" } );
           }
       }
  })

但很明显,这不是很漂亮。

你真正想要的是写自己的扩展方法,写下你自己的扩展方法,我的意思是无耻地窃取MoreLinq&#39; s(https://code.google.com/p/morelinq/source/browse/MoreLinq/MaxBy.cs)。您还可以使用:Point theMax = null; ForEach(x => theMax = (theMax == null || x.X + x.Y > theMax.X + theMax.Y ? x : theMax));

然后你可以这样做:Install-Package MoreLinq.Source.MoreEnumerable.MaxBy

请记住,Linq的美丽/力量是,在一天结束时,它是所有扩展方法。不要忘记你总是可以自己写你自己做你需要的东西。当然,MoreLinq项目通常拥有您所需要的。这是一个很棒的图书馆。

相关问题