我如何找到列表中具有相同值的所有项目并操作这些项目?

How can i find all the items in a List that have the same value and manipulate this items?

在代码之上:

[System.Serializable]
    public class PosDisPair //Name the pair however you like
    {
        public float Distance;
        public Vector3 Pos;
    }

然后:

private List<PosDisPair> pairList = new List<PosDisPair>();

private void FindDistances()
    {
        pairList = new List<PosDisPair>();

        for (int i = 0; i < objects.Count; i++)
        {
            PosDisPair pairToAdd = new PosDisPair();
            pairToAdd.Distance = Vector3.Distance(EndStartPoints[0].transform.position, objects[i].transform.position);
            pairToAdd.Pos = objects[i].transform.position;
            pairList.Add(pairToAdd);
        }

        pairList.Sort(delegate (PosDisPair a, PosDisPair b) {
            return (a.Distance.CompareTo(b.Distance));
        });

        Manip();
    }

最后一个

private void Manip()
    {
        List<float> samedistances = new List<float>();

        pairList = pairList.OrderBy(x => x.Distance).ToList();

        for (int i = 0; i < pairList.Count; i++)
        {
            if (pairList[i].Distance == pairList[i+1].Distance)
            {
                samedistances.Add(pairList[i].Distance);
            }
        }
    }

在 Manip 方法内部,我使用 OrderBy 按距离对列表进行排序 属性。 所以现在第一个距离是 0,所以我不需要做任何事情。

那么有3个项目,每一个的距离都是10。 但是每个item的位置都不一样

我想做的是每次从列表中取出所有相同距离的项目。例如,要取所有 10 的距离项目,然后从这三个项目中取一个随机项目。

接下来随机拾取两个 20 年代距离的物品之一,然后再次拾取相同距离的物品。

所以最后我会得到一个包含所有项目、距离和位置的列表,但从每个相同的距离来看,只有一个项目。

所以最后在 pairList 中我将有例如:

索引 0 = 距离 0

索引 1 = 距离 10

索引 2 = 距离 14.45456

索引 3 = 距离 20 . . . 索引 44 = 距离 134

相同的距离有彼此的位置。

例如:

索引 1 距离 10,位置 1,1,1

索引 2 距离 10,位置 2,1,1

索引 3 距离 10,位置 3,1,1

所以当它随机选择一个距离为 10 的位置时,它会在自己的位置上。

这将为您提供每个组中的第一个第一个 元素,其中您有多个元素。

var result = pairList.GroupBy(x => x.Distance).Select(y => y.FirstOrDefault());

要获得 随机 元素,试试这个:

Random rnd = new Random();
var resultRand = pairList.GroupBy(x => x.Distance).Select(y => y.ElementAt(rnd.Next(0, y.Count())));