简体   繁体   English

从列表中获取最小值

[英]Get minimum value from list

I have a class ABC like this 我有这样的ABC班

public class ABC{
public int Id {get;set;}
public int UserCount {get;set;}
}

Now I add following records to a list of type ABC 现在,我将以下记录添加到ABC类型的列表中

List<ABC> lstABC = new List<ABC>();
lstABC.Add(new ABC(){Id=1,UserCount=5});
lstABC.Add(new ABC(){Id=2,UserCount=15});
lstABC.Add(new ABC(){Id=3,UserCount=3});
lstABC.Add(new ABC(){Id=4,UserCount=20});

I've another list of type int 我还有另一个int类型的列表

List<int> lstIds = new List<int>();
lstIds.Add(1);
lstIds.Add(3);
lstIds.Add(4);

Now i want to find out the minimum value of UserCount by comparing both the list where Id in lstABC should match the items presesnt in lstIds . 现在我想找出的最小值UserCount通过比较两种情况的列表IdlstABC应该匹配项presesnt lstIds I can get the minimum value of UserCount by using loops but is there any another way to get the value in an optimized way by avoiding loops? 我可以通过使用循环来获取UserCount的最小值,但是还有其他方法可以通过避免循环来以优化的方式获取值?

You can use Enumerable.Join to link both lists: 您可以使用Enumerable.Join链接两个列表:

var joined = from id in lstIds
             join x in lstABC 
             on id equals x.Id 
             select x;
int minValue = joined.Min(x => x.UserCount);

This is more efficient than loops since Join uses a set to find matching items. 这比循环更有效,因为Join使用集合来查找匹配项。

There's more than one way to skin a cat, this is a little bit less efficient: 剥皮猫的方法不止一种,效率略低:

int minValue = lstABC.Where(x => lstIds.Contains(x.ID)).Min(x => x.UserCount);

Try below code: 试试下面的代码:

        int min = lstABC.Min(entry => entry.UserCount);
        var a = lstABC.Where(e => e.UserCount == min).FirstOrDefault();
        var resul = lstIds.Where(e => e.Equals(a.Id)).FirstOrDefault();
        var result = lstABC.Where(n =>n.Id == resul).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM