- Where Developers Learn, Share, & Build Careers


I have a list with an encoded I want to get the first element if and only then N = 1. Can it be done using lambda or some good build?

This works, but looks awesome:

  var blah = new list & lt; Object & gt; () {New object ()}; Var item = (blah.Count == 1? Blah [0]: zero);    

There are several LINQ extension methods.

  • If there is one element then an element exists, if any default will be returned, then returned it
  • If any default
  • returns the element in the given position or default ; T & gt; will be returned, if there are not many elements in the sequence will be returned

    for example (I have liked it for my own need):

      var item = blah.ElementAtOrDefault (0);   

    The best way to get your requirement depends on how strong this rule is:

    I want to get the first element if only If = 1

    If it is extraordinary that contains more than one element in the sequence, then use SingleOrDefault and you will be notified (error Log) if it gets out of hand.

    If it is important that you get first element and you never want another element, better use first and default because It has a meaningful name.

    If the element's index is important in the sequence and you (at present) need the first element, but it can change in future, ElementAtOrDefault Use.

  • Comments

    Popular posts from this blog

    Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

    java - How not to audit a join table and related entities using Hibernate Envers? -

    mongodb - CakePHP paginator ignoring order, but only for certain values -