简体   繁体   中英

Get minimum value from list

I have a class ABC like this

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

Now I add following records to a list of type 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

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 . 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?

You can use Enumerable.Join to link both lists:

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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