使用Linq更新嵌套属性

时间:2015-12-31 11:49:12

标签: c# .net linq

我有一个具有非原始属性的类 我需要更新父类的属性的一些子属性。

public class Parent
{
    public string Abc { get; set; }
    public Childclass Pos { get; set; }
}

public class Childclass
{
     public string Value { get; set; }
}

List<Parent> parents = new List<Parent>()

Parent p1 = new Parent();
p1.Pos.Value = "1";
parents.Add(p1);

Parent p2 = new Parent();
p2.Pos.Value = "2";
parents.Add(p2);

现在我需要更新父母Pos中的where Pos.Value == "2"

3 个答案:

答案 0 :(得分:4)

char init(void)
{
  UBRRH=(uint8_t) (UBRR_CALC>>8);
  UBRRL=(uint8_t) UBRR_CALC;
  UCSRB=(1<<RXEN)|(1<<TXEN);
  UCSRC=(1<<URSEL)|(3<<UCSZ0);
  return 0;
}

void send(unsigned char x)
{
  while(!(UCSRA&(1<<UDRE))){}
  UDR=x;
}

void sendstring(char *s)
{
  while(*s)
  {
    send(*s);
    s++;
  }
}

volatile uint16_t count=0;    //Main revolution counter   
volatile uint16_t rps=0;    //Revolution per second

void Wait()
{
  uint8_t i;

  for(i=0;i<2;i++)
  {
    _delay_loop_2(0);
  }
}

int main(void)
{
  Wait();
  Wait();
  Wait();
  Wait();

  //Init INT0
  MCUCR|=(1<<ISC01);   //Falling edge on INT0 triggers interrupt.
  GICR|=(1<<INT0);  //Enable INT0 interrupt

  //Timer1 is used as 1 sec time base
  //Timer Clock = 1/1024 of sys clock
  //Mode = CTC (Clear Timer On Compare)
  TCCR1B|=((1<<WGM12)|(1<<CS12)|(1<<CS10));

  //Compare value=976
  OCR1A=976;
  TIMSK|=(1<<OCIE1A);  //Output compare 1A interrupt enable

  //Enable interrupts globaly
  sei();

  while(1)
  {
  }
}

ISR(INT0_vect)
{
  //CPU Jumps here automatically when INT0 pin detect a falling edge
  count++;
}

ISR(TIMER1_COMPA_vect)
{
  //CPU Jumps here every 1 sec exactly!
  rps=count;
  send(rps);
  count=0;
}

如果您需要更新每件商品:

List<Parent> parents = new List<Parent>();

Parent p1 = new Parent();
p1.Pos = new Childclass() { Value = "1" };
parents.Add(p1);

Parent p2 = new Parent();
p2.Pos = new Childclass() { Value = "2" };
parents.Add(p2);

如果您只需更新第一项:

foreach (Parent parent in parents.Where(e => e.Pos.Value.Equals("2")))
    parent.Pos.Value = "new value";

答案 1 :(得分:1)

我想,你需要这样:

parents.Where(l => l.Pos.Value.Equals("2")).ToList().ForEach(i => i.Post.Value="updateValue");

答案 2 :(得分:0)

您可以使用exclude a specific dependency过滤掉该值,这将检索与谓词匹配的第一个元素:

var parent = parents.FirstOrDefault(
                x => x.Pos.Value.Equals("2", StringComparison.OrdinalIgnoreCase));
parent.Pos.Value = "3";

如果你有很多查找,也许你想要使用Dictionary<string, Parent>,其中密钥是一些不可变的值,如果可能的话,它会改变:

var keyToParent = new Dictionary<string, Parent>
{
    ["Abc"] = p1,
    ["Dfc"] = p2
};

if (!keyToParent.ContainsKey("Abc"))
    return;

var retrievedParent = keyToParent["Abc"];
retrievedParent.Pos.Value = "3";