0

是否可以使用 linq 以更简洁的方式编写它。

//retrieved from db
List<User> existingList = new List<User>()
{
new User() {
Id = 1,
Name = "test1",
City = "City1"
},
new User() {
Id = 2,
Name = "test2",
City = "City"
}
};

//modified by ui
List<User> modifiedlist = new List<User>()
{
new User() {
Id = 1,
Name = "test1",
City = "City1"
},
new User() {
Id = 3,
Name = "test3",
City = "City3"
}
};

**in db: (Going By modified list) 我需要添加用户 3 并删除用户 2 并且不要打扰 1。

**对于删除 user2,我正在遍历现有列表,如果修改后的列表中不存在,则删除 2。**对于添加 user3,我正在遍历修改后的列表,如果现有列表中不存在,则添加 3

4

2 回答 2

1

这看起来正是您所需要的。
如何:查找两个列表之间的集合差异 (LINQ):

        List<int> existingList = new List<int>() { 1, 2 };
        List<int> modifiedList = new List<int>() { 1, 3 };

        var usersToDelete = existingList.Except(modifiedList).ToList(); //contains '2'
        var usersToAdd = modifiedList.Except(existingList).ToList(); //contains '3'
于 2012-08-31T02:30:16.307 回答
-1

如果您知道它是 1,2,3 并且您知道您想要它 1,4 - 那么您只需 RemoveAt(2) 删除 3,然后将 [1] 设置为 4 将 2 更改为 4。 RemoveAt 是比 Remove 更快,因为它按索引进行。

var list = new List<int> {1,2,3};

list.RemoveAt(2);
list[1] = 4;

但是当然,如​​果您不知道要删除的号码是否存在,以及它们存在的位置,您显然需要搜索它们......

现在,假设您知道列表已排序,并且很大。toRemove让我们考虑这样一种情况:列表有 10,000 个元素{ 0,2,5,6,8,...} ,6,7,...}

那么除了时间之外,您实际上可以迭代列表一次toRemove.Count,如下所示:

int j = 0;

for (int i = 0; i < list.Count && j < toRemove.Count; i++)
{
    if (list[i] == toRemove[j])
    {
        list.RemoveAt(i);
        j++;
        i--;
    }
}

如果列表可能包含重复的数字 {1, 4, 4, 5, 7,...} 并且您想以不存在单个 4 的方式删除 4,那么您需要执行以下操作:

int j = 0;

for (int i = 0; i < list.Count && j < toRemove.Count; i++)
{
    var currRemove = toRemove[j];

    while (list[i] == currRemove)
    {
        list.RemoveAt(i);
        i--;
    }

    j++;
}

编辑:

如果你想让它更干净、效率更低,你可以这样做:

list = list.Except(toRemove).Union(toAdd).ToList();

如果您不想添加已经存在的项目:

var tmp = list.Except(toRemove);
list = list.Union(toAdd.Except(tmp)).ToList();

但我必须说这会非常慢,你可能想重新考虑使用列表,也许使用 HashTable 或Dictionary

于 2012-08-31T02:02:50.847 回答