2

I want to get Boolean value if queue contains object having particular value in the properties.

e.g)

public class Order
{
    public string orderType { get; set; }
    public string sCode { get; set; }  
    public int iNum { get; set; }
    ...omit... 
}
Queue<Order> queueSendOrder = new Queue<Order>();

Then, how to check if Queue contains or not if contains any object having sCode="Code1", iNum=1?

Thank you.

6
  • 3
    Queue is data structure which is not supposed to be used for traversing through all its items. Even if you manage to do that - it doesn't make much sense. Why don't you just use an array? Commented Apr 26, 2018 at 16:24
  • 2
    @YeldarKurmangaliyev Queue<T> implements IEnumerable<T> so it's perfectly reasonable to iterate over the contents. Commented Apr 26, 2018 at 16:29
  • @DavidG Still, checking whether a queue has something is not a usual thing to do... At least I've never done it. Commented Apr 26, 2018 at 16:30
  • 1
    @Sweeper True, but "unusual" doesn't mean you're not supposed to do it. Commented Apr 26, 2018 at 16:30
  • 2
    Why not just use the IEnumerable extension methods? You can do something like queueSendOrder.Any(o => o.iNum == 1 && o.sCode == "Code1") or var matchingItems = queueSendOrder.Where(o => o.sCode == "Code1").ToList(); Commented Apr 26, 2018 at 16:33

1 Answer 1

5

Using the Linq Any() extension method, this is quite simple:

var containsCode1 = queueSendOrder.Any(o => o.sCode == "Code1");
var containsNum1 = queueSendOrder.Any(o => o.iNum == 1);

Or both:

var containsCode1AndNum1 = queueSendOrder.Any(o => 
    o.sCode == "Code1"
    && o.iNum == 1);

Side note: It's considered bad practice these days to use Hungarian notation to denote types. So sCode should really just be Code and iNum would be Num (though I would choose a better name than that)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.