C#Lambda表达式未返回预期结果

时间:2009-08-21 18:32:25

标签: c# linq linq-to-sql lambda

我正在使用lamda表达式来过滤查询。

基本上,我有由段组成的行,这些段被标记为已删除,已插入或为空。

我想要返回的是已被标记为已删除但其任何兄弟未标记为已删除的段。例如,

Line: "Soylent Green is people!" Broken into 2 segments... 
Segment 1: "Soylent Green " (marked as deleted)
Segment 2: "is people!" (not marked as deleted)

应该返回我的段1.但是下一个例子,

Line: "Open the pod bay doors Hal!" Broken into 3 segments...
Segment 1: "Open the " (marked as deleted)
Segment 2: "pod bay " (marked as deleted)
Segment 3: "doors Hal!" (marked as deleted)

不应该返回任何细分。请参阅以下代码:

return seg => seg.ModType == Deleted &&
              seg.Line.Segments.Any(segs => segs.ID != seg.ID && 
              segs.ModType != Deleted);

谢谢,我感谢任何帮助或建议,为什么这不起作用。

3 个答案:

答案 0 :(得分:2)

我认为它会是这样的:

return s =>  from segment in s.Line.Segments 
             where segment.ModType == Deleted 
                && segment.Line.Segments.Any(segs => segs.ModType != Deleted)
             select segment

答案 1 :(得分:0)

使用Where(),而不是Any(),它将返回一个IEnumerable对象。就像Jon说的那样,Any()返回一个布尔值。

答案 2 :(得分:0)

由于ModType可以为空,因此它没有返回我期望的内容。代码应该是......

return seg => seg.ModType == Deleted &&
          seg.Line.Segments.Any(segs => segs.ID != seg.ID && 
          (segs.ModType != Deleted || segs.ModType == null));
  

感谢所有回复并提出意见和建议的人!