Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3348298
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T01:31:33+00:00 2026-05-18T01:31:33+00:00

When dealing with an enumeration containing none, one or many of an item the

  • 0

When dealing with an enumeration containing none, one or many of an item the foreach loop makes it easy to iterate over them and LINQ Select makes it easy to project items from the enumeration.

        foreach (var attr in p.GetCustomAttributes().OfType<A>()) ...

When dealing with an enumeration containing none or just one of an item things are a little trickier. You can use the same foreach loop but that doesn’t ensure that there is only one of the items present and it may execute more than once.

You could add .Take(1) to make it clear that you only want up to one and to ensure that the loop only executes once. But that isn’t going to throw an Exception if there is more than one.

        foreach (var attr in ...().Take(1)) ...

You could add a check beforehand to make sure there is only one, or perhaps a new code contract to check, but that’s rather messy:

        Contract.Requires(p..GetCustomAttributes().OfType<A>().Count() < 2);
        foreach (var attr in p.GetCustomAttributes().OfType<A>()) ...

You could even create a new extension method .ZeroOrOne<T>() which returns the first element in an enumeration and then throws an exception if you ask for more.

        foreach (var attr in ...().ZeroOrOne()) ...

Or you can get rid of the loop, use .SingleOrDefault() and then test for null which is clearly the clearest of all in terms of intent and ensuring that the loop executes zero or one times but again it’s more code, it’s less ‘declarative’ and it’s not ‘composable’:

            var attr =  p.GetCustomAttributes().OfType<A>().SingleOrDefault();
            if (attr != null)
            {
               ...

So to the question: Which of the above (or other suggestions) do people prefer and why? Most programmers used to procedural code will naturally prefer the if statement but for those of you deep into functional programming, do you have a better approach?

Some other languages have clean techniques to handle this, e.g. F#’s array patterns can match zero, one, or more, or fail. Is there a case for a forone construct in the C# language that would be equivalent to checking that there are zero or one in the enumeration and then executing it?

[The specific example here is getting custom attributes where the attribute has been marked to not allow multiple but the question is more generally about handling the zero/one case.]

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T01:31:33+00:00Added an answer on May 18, 2026 at 1:31 am

    Edit:

    With that clarification, I would favour the ZeroOrOne<T> extension method inside a loop. It would essentially do what you did with the explicit test for more than one. I am a little torn whether it should return IEnumerable<T> or Nullable<T> though. I guess it depends on how you would typically be using the result.

    Old Answer

    It sounds to me like you want the .Single extension method rather than .SingleOrDefault.

    You said:

    You could add .Take(1) to make it clear that you only want up to one and to ensure that the loop only executes once. But that isn’t going to throw an Exception if there is more than one.

    What you are describing is .Single. Plus, it is short and demonstrates very clearly your intent.

    var attr = p.GetCustomAttributes().OfType<A>().Single();
    // will throw exception if there is more than one attribute of type A
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Other questions dealing with use of match_parent pre 2.2 have answers stating one should
when dealing with wildcards such as setting/adding a generic item to a certain container
Dealing with go's funcs I discovered that one can't force the compiler to control
When dealing with something like a List<string> you can write the following: list.ForEach(x =>
Dealing with classes (nested etc) does not look easy in Python , surprisingly !
When dealing with swing components, and when changing the components during runtime, one (often)
Dealing with an employee that went over my head
When dealing with pointers, pointers to one past the end have (mostly) defined behavior:
When dealing with persistant MySQL connections, the one problem is that they get dropped
I am dealing with a legacy application and the database is in Oracle. One

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.