简体   繁体   中英

Using .Any from System.Linq on array to find a string

I'm trying to find out whether a particular cell in my array contains part of a given string. Since arrays don't use .Contains I'm using .Any, but it seems my understanding of how .Any works is too hazy to get it right.

public void ProcessCSV (string typeName) {

    for (int y = 0; y < CSVReader.grid.GetUpperBound(1); y++) {
        if (CSVReader.grid[0,y] != null) {
            if ((CSVReader.grid[0,y].Any(s => typeName.Contains(s)))) {
                  // (add it to a new list)

So I'm feeding in strings like "Pork", "Farm" etc. Sometimes it seems to work perfectly, eg if typeName is "Farm" I only get back rows from the array that include that string in [0, y]. But at other times, if I'm using Farm, another string or random gibberish, it just returns every single row that has any string at all.

What's actually happening when I call .Any in this way? Is there some alternate method I could use?

You probably have it the wrong way around.

Any will return a boolean indicating whether any element in the sequence meets the condition. When you type Any(s => ...) , s is the element from the sequence that gets checked.

So when you type:

.Any(s => typeName.Contains(s))

...you are essentially asking:

Is any element from the sequence contained in the string typeName ?

For example, if typeName is Pork , Any() will only return true when "Pork".Contains("ork") . You probably meant it the other way around:

.Any(s => s.Contains(typeName))

Does any element contain the string typeName ?

So that "Pork and beef".Contains("Pork") returns true .


If you want the first element (instead of a boolean truth) from the sequence that that meets the condition, use FirstOrDefault (or, when you know there is always at least one, you can use First instead). For example:

.FirstOrDefault(s => typeName.Contains(s))

Return the first element from the sequence that is contained in the string typeName ; or the default value when there is none.

Or, the other way around (which I still think you meant):

.FirstOrDefault(s => s.Contains(typeName))

Return the first element from the sequence that contains the string typeName ; or the default value when there is none.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM