[英]Find the item with the lowest value of a property within a list
Let's say I have this class:假设我有这门课:
class Person {
public int ID;
public string Name;
}
And then I have a list of Person's.然后我有一个人的名单。
List<Person> persons = new List<Person>();
Which is filled with alot of random persons.其中充满了很多随机的人。 How do I query the list to get the person with the lowest ID?
如何查询列表以获取 ID 最低的人? The objects in the list is in a random order so the person with the lowest ID might not be the very first element.
列表中的对象按随机顺序排列,因此 ID 最低的人可能不是第一个元素。 Can I achieve this without sorting the list first?
我可以在不先对列表进行排序的情况下实现这一目标吗?
this is without sorting the list and just iterates the list once.这是没有对列表进行排序,只是迭代列表一次。
Person minIdPerson = persons[0];
foreach (var person in persons)
{
if (person.ID < minIdPerson.ID)
minIdPerson = person;
}
You can use MinBy
method from More Linq library:您可以使用 More Linq 库中的
MinBy
方法:
var person = persons.MinBy(x => x.ID);
If you can't use a third party library you can get the min ID first and then get the person that has the min ID:如果您不能使用第三方库,您可以先获取 min ID,然后获取具有 min ID 的人:
var minID = person.Min(x => x.ID);
var person = persons.First(x => x.ID == minID);
Use the Min extension method of LINQ:使用LINQ的Min扩展方法:
persons.Min(p => p.ID)
EDIT:编辑:
My bad, the previous method returns only the lowest ID, so in case you'd like to use only built-in LINQ methods, here you go:糟糕,前面的方法只返回最低的 ID,所以如果你只想使用内置的 LINQ 方法,你可以这样做:
persons.Aggregate(
(personWithMinID, currentPerson) =>
currentPerson.ID <= personWithMinID.ID ? currentPerson : personWithMinID)
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.