问题描述:

I have an IEnumerable<TextBox>. One of the element has a Tag. I want to filter my first IEnumerable in this way:

IEnumerable<TextBox> longDescContainersTag =

longDescContainers.Where(i => i.Tag == "DescrOp");

The where condition doesn't work, it simply doesn't find any TextBoxes, the sequence is empty. But if I do a quick watch of longDescContainers it has an element with Tag "DescrOp".

Do you have some suggestions?

网友答案:

It's not clear from your question but I'm assuming your where-condition is correct but you don't get any result although the source collection does contain an element where the condition should match.

I say should because Control.Tag is an object, and using i.Tag == "DescrOp" will do a comparison by reference instead of by value.

This might or might not return true even if the strings are equal. What you should do is cast i.Tag to string first, i.e. (string)i.Tag == "DescrOp".

网友答案:

1- Are you sure .Tag contains string value? In some cases when we watching the watch window shows name of an object. Actually cals "ToString()" method of object and shows it. I think you can use this code:

IEnumerable<TextBox> longDescContainersTag = 
    longDescContainers.Where(i => i.Tag.ToString() == "DescrOp");

2- Are you sure all objects in "longDescContainers" is of type "TextBox"? I don't know what is "longDescContainers" object, but in some container objects we need to cast their sub items(controls) like this code "longDescContainers.cast<TextBox>().where(....)". If you not sure all objects in "longDescContainers" is TextBox you can try this code:

    IEnumerable<TextBox> longDescContainersTag = longDescContainers.
    Where(i => i.GetType() == typeof(TextBox) && i.Tag == "DescrOp").
Select(t=> (TextBox)t);

If longDescContainersTag contains even any object of type "TextBox" that tag is "DescrOp" the code above returns it.

You can use compound of "1" and "2" and use the following code:

    IEnumerable<TextBox> longDescContainersTag = longDescContainers.
    Where(i => i.GetType() == typeof(TextBox) && i.Tag.ToString() == "DescrOp")
.Select(t=> (TextBox)t);
网友答案:

Assuming that your longDescContainers is a collection of TextBox. I suspect that comparing Tag (object) to "DescrOp" (string) fails.. Try to use ToString()..

IEnumerable<TextBox> longDescContainersTag = longDescContainers.Where(i => i.Tag!=null && i.Tag.ToString() == "DescrOp");
相关阅读:
Top