1

我正在尝试编写一个程序,向用户显示重复记录以更正数据或删除重复行。它有效,但我必须在我的 lambda 表达式中放置一个 Where 子句才能使其正常工作。我怎样才能删除这个无用的条款?

其中(d => d.Id > 0)在第 22 行。

public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            List<Person> dt = new List<Person>();
            dt.Add(new Person() { Id = 1, Name = "MICHAEL JACKSON", Age = 50 });
            dt.Add(new Person() { Id = 2, Name = "MICHAEL JACKSON", Age = 51 });
            dt.Add(new Person() { Id = 3, Name = "JOHN LENNON", Age = 40 });
            dt.Add(new Person() { Id = 4, Name = "JOHN LENNON", Age = 41 });
            dt.Add(new Person() { Id = 5, Name = "ELVIS PRESLEY", Age = 42 });

            var duplicates = dt.AsEnumerable().GroupBy(r => r.Name).Where(gr => gr.Count() > 1).ToList();
            if (duplicates.Any())
            {
                var query = duplicates.SelectMany(c => c.Where(d => d.Id > 0)).AsQueryable();

                foreach (var item in query)
                    Console.WriteLine(String.Format("{0} - {1}", item.Name, item.Age));
            }
            else
                Console.WriteLine("No records duplicates.");

            Console.ReadLine();
        }
    }

这只是示例代码,我的代码进行了很多其他检查,但是如果有人知道如何删除此子句,那将对我非常有帮助。我认为这可能会影响性能。

4

3 回答 3

2

这在这里也有效:

    List<Person> dt = new List<Person>();
    dt.Add(new Person() { Id = 1, Name = "MICHAEL JACKSON", Age = 50 });
    dt.Add(new Person() { Id = 2, Name = "MICHAEL JACKSON", Age = 51 });
    dt.Add(new Person() { Id = 3, Name = "JOHN LENNON", Age = 40 });
    dt.Add(new Person() { Id = 4, Name = "JOHN LENNON", Age = 41 });
    dt.Add(new Person() { Id = 5, Name = "ELVIS PRESLEY", Age = 42 });

    var duplicates = dt.GroupBy(r => r.Name).Where(gr => gr.Count() > 1).ToList();
    if (duplicates.Any())
    {

        foreach (var item in duplicates)
            Console.WriteLine(String.Format("{0} - {1}", item.Key, string.Join(",", item.Select(p => p.Age))));
    }
    else
        Console.WriteLine("No records duplicates.");

    Console.ReadLine();
于 2012-12-13T17:21:04.827 回答
1

duplicates是因为是按对象分组的。如果您只想显示名称,请尝试此操作:

var query = duplicates.Select(c => c.Key);
foreach (var item in query)
    Console.WriteLine(String.Format("{0}", item));

如果你想显示重复的年龄,试试这个:

var query = duplicates.SelectMany(i => i);
foreach (var item in query)
    Console.WriteLine(String.Format("{0} - {1}", item.Name, item.Age));
于 2012-12-13T17:19:55.010 回答
1

这对我有用。

            var query = duplicates.SelectMany(c => c).AsQueryable();
于 2012-12-13T17:22:23.877 回答