Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
linq到对象查询:选择不存在其他值的对象_Linq - Fatal编程技术网

linq到对象查询:选择不存在其他值的对象

linq到对象查询:选择不存在其他值的对象,linq,Linq,帮助linq查询选择每个日期只有一个值的项的对象。 因此,在以下列表中: 1) 将选择2011-1-4,因为其项目均为25 2) 2011-1-1将不会被选择,因为它包含项目22和25 3) 将选择2011-1-2和2011-1-3,因为它们只有一个项目 public class MyClass { public DateTime date { get; set; } public int item { get; set; } }

帮助linq查询选择每个日期只有一个值的项的对象。 因此,在以下列表中:

1) 将选择2011-1-4,因为其项目均为25

2) 2011-1-1将不会被选择,因为它包含项目22和25

3) 将选择2011-1-2和2011-1-3,因为它们只有一个项目

    public class MyClass
    {
        public DateTime date { get; set; }
        public int item { get; set; }
    }
    static void Main(string[] args)
    {
        List<MyClass> classes = new List<MyClass> 
        {
        { new MyClass() { date = new DateTime(2011, 1, 1), item = 22 } },
        { new MyClass() { date = new DateTime(2011, 1, 1), item = 25 } },
        { new MyClass() { date = new DateTime(2011, 1, 2), item = 23 } },
        { new MyClass() { date = new DateTime(2011, 1, 3), item = 24 } },
        { new MyClass() { date = new DateTime(2011, 1, 4), item = 25 } },
        { new MyClass() { date = new DateTime(2011, 1, 4), item = 25 } },
        };
    }

这是一些未经编辑的丑陋,我已经通过Linqpad运行,似乎符合您的要求

var query = classes.GroupBy(c => c.date)
                   .Select(g => g.GroupBy(c => c.item))
                   .Where(sg => sg.Count() == 1)
                   .SelectMany(sg => sg)
                   .SelectMany(g => g)
                   .Select(c => c.date)
                   .Distinct();

根据您的要求返回日期1/2、1/3和1/4。

这似乎可行,但我不会对此感到满意:

var results = from m in classes
              group m by new { m.date } into x
              where x.GroupBy(y => y.item).Count() == 1
              select x;

您的查询只返回1/2和1/3。用户还想要1/4,因为虽然它有两个对象,但每个对象的项都有相同的值。@Anthony我想我现在得到了!你认为呢?它现在返回适当的日期。var results=classes.GroupBy(m=>m.date);var q=结果中的n,其中n.All(r=>r.item==n.First().item)选择n;你确实解决了问题,但我的问题太多、太少、还是太多了。@tim,如果使用我的版本,你想要的是完整的对象,而不仅仅是日期,你可以在第二次
SelectMany
@tim后切断我的查询,这是StackOverflow Goldilocks。
var query = classes.GroupBy(c => c.date)
                   .Select(g => g.GroupBy(c => c.item))
                   .Where(sg => sg.Count() == 1)
                   .SelectMany(sg => sg)
                   .SelectMany(g => g)
                   .Select(c => c.date)
                   .Distinct();
var results = from m in classes
              group m by new { m.date } into x
              where x.GroupBy(y => y.item).Count() == 1
              select x;