在列表中查找具有最低属性值的项目

时间:2014-11-05 10:05:23

标签: c# .net list

我们说我有这堂课:

class Person {
   public int ID;
   public string Name;
}

然后我有一份人员名单。

List<Person> persons = new List<Person>();

其中充满了很多随机的人。如何查询列表以获取ID最低的人?列表中的对象是随机顺序,因此ID最低的人可能不是第一个元素。我可以在没有先排序列表的情况下实现这一目标吗?

4 个答案:

答案 0 :(得分:7)

这是没有对列表进行排序,只是迭代列表一次。

Person minIdPerson = persons[0];
foreach (var person in persons)
{
    if (person.ID < minIdPerson.ID)
        minIdPerson = person;
}

答案 1 :(得分:4)

您可以使用More Linq库中的MinBy方法:

var person = persons.MinBy(x => x.ID);

如果您不能使用第三方库,您可以先获取最小ID,然后获取具有最小ID的人:

var minID = person.Min(x => x.ID);
var person = persons.First(x => x.ID == minID);

答案 2 :(得分:2)

使用LINQ的 Min 扩展方法:

persons.Min(p => p.ID)

修改

我的不好,前面的方法只返回最低的ID,所以如果你只想使用内置的LINQ方法,请转到:

persons.Aggregate(
    (personWithMinID, currentPerson) =>
        currentPerson.ID <= personWithMinID.ID ? currentPerson : personWithMinID)

答案 3 :(得分:0)

List<AnswerInfo> answerinfo;

Public void SampleFunction()
{
        answerinfo = new List<AnswerInfo>();
        //custom hash table storing elapsed time for all users
        float LocalScoreTime = (float.Parse)((string)local.CustomProperties["elapsedTime"]);

        AnswerInfo objc = new AnswerInfo();

        if (CorrectAnswer)
        {
            foreach (PhotonPlayer _player in PhotonNetwork.otherPlayers)
            {
                objc.ID = _player.ID;
                objc.AnsCorrect = (bool)_player.CustomProperties["RemoteAnswer"];
                objc.AnsTime = (float.Parse)((string)_player.CustomProperties["elapsedTime"]);

                answerinfo.Add(objc);
            }
            //This can work too and can be used in future
            //var minID = answerinfo.Min(x => x.AnsTime);
            //var person = answerinfo.First(x => x.AnsTime == minID);

            AnswerInfo minTimePerson = answerinfo[0];
            float minTime = 30;
            foreach (AnswerInfo user in answerinfo)
            {
                if (user.AnsCorrect)
                {
                    if (user.AnsTime < minTime)
                    {
                        minTime = user.AnsTime;
                        minTimePerson = user;
                    }
                }
            }
            Debug.LogFormat("Remote User ID with correct Answer: {0} and lowest time {1}",minTimePerson.ID,minTimePerson.AnsTime);
            if(LocalScoreTime < minTimePerson.AnsTime)
            {
                local.AddScore(1);
                localplayerscore_textfield.color = Color.green;
            }
        }
}
[Serializable]
public class AnswerInfo
{
    public bool  AnsCorrect;
    public float AnsTime;
    public int ID;
}