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<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;
}
Use the Min extension method of LINQ:
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:
persons.Aggregate(
(personWithMinID, currentPerson) =>
currentPerson.ID <= personWithMinID.ID ? currentPerson : personWithMinID)
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:
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:
var minID = person.Min(x => x.ID);
var person = persons.First(x => x.ID == minID);