【问题标题】:LINQ: find items in a list that have frequency = 1LINQ:在列表中查找频率 = 1 的项目
【发布时间】:2012-07-06 10:13:19
【问题描述】:

我正在努力完成以下任务。任何建议将不胜感激!

我有一个 Person 对象列表,如下所示:

public class Person {
     private string firstname {get; set}
     private string lastname {get; set}
     private string zipcode {get; set;}
     private string id {get; set;}
     private int freq = 1;

     public Person(...) {...}
}

List<Person> PersonList = new List<Person>; //Gets populated with Person objects

我想找到所有在他们的邮政编码中具有唯一姓名的人。

到目前为止,我已经尝试对(名字、姓氏、邮政编码)的所有不同组合进行频率计数,然后选择频率 = 1 的组合。但是,我随后丢失了有关这些人 ID 的所有信息.尽管进行了分组操作,但我需要一种方法来保留原始 Person 对象。

下面是我上面提到的频率计数,但这不是我要寻找的结果:

var QueryFreqAnalysis =
                        from p in PersonList
                        group p by new { p.firstName, p.lastName, p.zipcode } into g
                        select new {
                            fName = g.Key.firstname,
                            lName = g.Key.lastname,
                            zip3 = g.Key.zipcode,
                            freq = g.Sum(p => p.freq)
                        };

正如我所提到的,即使我现在可以在 g 中选择 freq = 1 的组,我也丢失了有关人员 ID 的所有信息。

我希望我已经把问题说清楚了。提前感谢您的任何建议!

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    from p in PersonList
    // Group by name and zip
    group p by new { p.firstName, p.lastName, p.zipcode } into g
    // Only select those who have unique names within zipcode
    where g.Count() == 1
    // There is guaranteed to be one result per group: use it
    let p = g.FirstOrDefault()
    select new {
        fName = p.firstname,
        lName = p.lastname,
        zip3 = p.zipcode,
        id = p.id
    }
    

    【讨论】:

    • 我建议将 select new ... 替换为 select p;
    • 这正是我想要的——非常感谢您的慷慨帮助!我不知道 FirstOrDefault() 函数...非常有帮助!
    • Erez Robinson:顺便说一句,我从 Person 对象中删除了“freq”字段,并根据您的建议将“select new...”替换为“select p”。谢谢!
    【解决方案2】:

    我知道你可能只需要并且想要一个 linq 答案:)
    但我只需要写一个非 linq 的:

    var dict = new Dictionary<string, Person>(PersonList.Count);
    
            var uniqueList = new List<Person>();
    
            foreach (var p in PersonList)
            {
                var key = p.firstname + p.lastname + p.zipcode;
                if (!dict.ContainsKey(key))
                    dict.Add(key, p);
                else
                    dict[key] = null;
            }
    
            foreach (var kval in dict)
            {
                if (kval.Value != null)
                    uniqueList.Add(kval.Value);
            }
    
            return uniqueList;
    

    也可以使用哈希码。

    【讨论】:

    • 谢谢。我将使用 StriplingWarrior 发布的 LINQ 解决方案,但我也感谢您的帮助 :)
    猜你喜欢
    • 2022-08-15
    • 2015-04-16
    • 2013-10-05
    • 2010-11-13
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多