如何过滤列表?

Chr*_*ris 0 c# sorting loops generic-list

这是一种方法,应该将已分配的用户从列表中取出,并将未分配的用户保留在列表中.GuidList在按钮点击时添加了userId.profileList用于填充gridView.

这是代码:

private VList<VW_profiles> FilterAssigned(VList<VW_profiles> profileList)
{
    VList<VW_profiles> sortedList = new VList<VW_profiles>();
    foreach(VW_profiles profile in profileList)
    {
        if(GuidList.Count > 0)
        {
            foreach(Guid userId in GuidList)
            {
                if(profile.UserId != userId)
                {
                    sortedList.Add(profile)
                }
            }
        }       
        else
        {
            sortedList = profileList;
        }
    }
    return sortedList;
}
Run Code Online (Sandbox Code Playgroud)

现在这是我的问题.Everythings似乎工作得很好,直到profileList中的所有项目也被添加到GuidList中.然后我们不再对两个Guid ID进行否定,而是再次开始添加所有人.有没有人有任何关于如何做到这一点的建议是一种更有效的方法,并且一旦我们把所有事情都拿出来就避免加入.

谢谢!

Sam*_*ell 6

如果VList<T>List<T>,那么你可以这样做:

profileList.RemoveAll(profile => GuidList.Contains(profile.UserId));
Run Code Online (Sandbox Code Playgroud)

如果性能是一个问题,并且有很多Guid要删除,那么你可以使GuidList成为一个HashSet<Guid>.

编辑基于注释:如果您不想修改原始列表,请执行以下操作:

var filtered = new VList<VW_profiles>(
    profileList.Where(profile => !GuidList.Contains(profile.UserId)));
Run Code Online (Sandbox Code Playgroud)

编辑如果你没有使用a List<T>,这里有一个方法,你可以使用可调整大小的列表实现IList<T>和一个你可以在数组(T[])上使用.通过仅从列表末尾删除项目,对于大多数实现,O(n²)算法将是O(n)IList<T>.

public static void RemoveAll<T>(this IList<T> list, Predicate<T> match)
{
    if (list == null)
        throw new ArgumentNullException("list");
    if (match == null)
        throw new ArgumentNullException("match");
    if (list is T[])
        throw new ArgumentException("Arrays cannot be resized.");

    // early out
    if (list.Count == 0)
        return;

    // List<T> provides special handling
    List<T> genericList = list as List<T>;
    if (genericList != null)
    {
        genericList.RemoveAll(match);
        return;
    }

    int targetIndex = 0;
    for (int i = 0; i < list.Count; i++)
    {
        if (!match(list[i]) && targetIndex != i)
        {
            list[targetIndex] = list[i];
            targetIndex++;
        }
    }

    // Unfortunately IList<T> doesn't have RemoveRange either
    for (int i = list.Count - 1; i >= targetIndex; i--)
    {
        list.RemoveAt(i);
    }
}

public static void RemoveAll<T>(ref T[] array, Predicate<T> match)
{
    if (array == null)
        throw new ArgumentNullException("array");
    if (match == null)
        throw new ArgumentNullException("match");

    int targetIndex = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (!match(array[i]) && targetIndex != i)
        {
            array[targetIndex] = array[i];
            targetIndex++;
        }
    }

    if (targetIndex != array.Length)
    {
        Array.Resize(ref array, targetIndex);
    }
}
Run Code Online (Sandbox Code Playgroud)