2013-05-02 70 views
0

我遍历类型为“prvEmployeeIncident”的对象的列表。我如何找到一个对象,我正在迭代通过

对象具有以下属性:

public DateTime DateOfIncident { get; set; } 
public bool IsCountedAsAPoint; 
public decimal OriginalPointValue; 
public bool IsFirstInCollection { get; set; } 
public bool IsLastInCollection { get; set; } 
public int PositionInCollection { get; set; } 
public int DaysUntilNextPoint { get; set; } 
public DateTime DateDroppedBySystem { get; set; } 
public bool IsGoodBehaviorObject { get; set; } 

我的列表由DateOfIncident属性排序。我想找到下一个对象up列表IsCounted == true并将其更改为IsCounted = false。

一个问题:

1)如何在列表中找到该对象?

+0

可能是下一个匹配的项目。 – Romoku 2013-05-02 17:16:00

回答

1

如果我理解正确,这可以通过一个简单的foreach循环来解决。我不完全理解你对“向上”的强调,因为你并没有真的提出一个列表,而是遍历它。无论如何,下面的代码片段找到了IsCounted为true的第一个事件并将其更改为false。如果您从给定位置开始,请将每个循环更改为for循环,并从i = currentIndex开始,退出条件为i < MyList.Count。保留break语句以确保您只修改一个事件对象。

foreach (prvEmployeeIncident inc in MyList) 
    { 
     if (inc.IsCountedAsAPoint) 
     { 
      inc.IsCountedAsAPoint = false; 
      break; 
     } 
    } 
3

如果我正确理解你的问题,你可以使用LINQ FirstOrDefault

var nextObject = list.FirstOrDefault(x => x.IsCountedAsAPoint); 

if (nextObject != null) 
    nextObject.IsCountedAsAPoint = false; 
+1

加速+1几秒... – DarkSquirrel42 2013-05-02 17:20:01

+0

我可以在集合中使用lambda,我已经在迭代中间了吗? – 2013-05-02 17:22:42

+0

@ user1073912:它不应该是因为它不是更好的性能,但请你能发布你的代码以获得更多的理解吗? – 2013-05-02 17:24:38

0

您可以使用List(T).FindIndex搜索该名单。

例子:

public class Foo 
{ 
    public Foo() { } 

    public Foo(int item) 
    { 
     Item = item; 
    } 

    public int Item { get; set; } 
} 

var foos = new List<Foo> 
       { 
        new Foo(1), 
        new Foo(2), 
        new Foo(3), 
        new Foo(4), 
        new Foo(5), 
        new Foo(6) 
       }; 

foreach (var foo in foos) 
{ 
    if(foo.Item == 3) 
    { 
     var startIndex = foos.IndexOf(foo) + 1; 
     var matchedFooIndex = foos.FindIndex(startIndex, f => f.Item % 3 == 0); 
     if(matchedFooIndex >= startIndex) // Make sure we found a match 
      foos[matchedFooIndex].Item = 10; 
    } 
} 

New collection

只要确保你不要修改列表本身,因为这会抛出异常。