如何删除lambda表达式的Where条件?

时间:2012-12-13 17:16:08

标签: c# linq lambda

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

第22行的(d => d.Id> 0)

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();
        }
    }

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

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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));

答案 2 :(得分:1)

这适合我。

            var query = duplicates.SelectMany(c => c).AsQueryable();