Get Count in List of instances contained in a stri

2019-04-10 23:11发布

I have a string containing up to 9 unique numbers from 1 to 9 (myString) e.g. "12345"

I have a list of strings {"1"}, {"4"} (myList) .. and so on.

I would like to know how many instances in the string (myString) are contained within the list (myList), in the above example this would return 2.

so something like

count = myList.Count(myList.Contains(myString));

I could change myString to a list if required.

Thanks very much

Joe

6条回答
Summer. ? 凉城
2楼-- · 2019-04-10 23:50

try

var count = myList.Count(x => myString.ToCharArray().Contains(x[0]));

this will only work if the item in myList is a single digit

Edit: as you probably noticed this will convert myString to a char array multiple times so it would be better to have

var myStringArray = myString.ToCharArray();
var count = myList.Count(x => myStringArray.Contains(x[0]));
查看更多
来,给爷笑一个
3楼-- · 2019-04-10 23:56

Try

count = myList.Count(s => s==myString);
查看更多
ゆ 、 Hurt°
4楼-- · 2019-04-10 23:57

It is not perfectly clear what you need, but these are some options that could help:

myList.Where(s => s == myString).Count()

or

myList.Where(s => s.Contains(myString)).Count()

the first would return the number of strings in the list that are the same as yours, the second would return the number of strings that contain yours. If neither works, please make your question more clear.

查看更多
不美不萌又怎样
5楼-- · 2019-04-11 00:01

This is one approach, but it's limited to 1 character matches. For your described scenario of numbers from 1-9 this works fine. Notice the s[0] usage which refers to the list items as a character. For example, if you had "12" in your list, it wouldn't work correctly.

string input = "123456123";
var list = new List<string> { "1", "4" };
var query = list.Select(s => new
                {
                    Value = s,
                    Count = input.Count(c => c == s[0])
                });

foreach (var item in query)
{
    Console.WriteLine("{0} occurred {1} time(s)", item.Value, item.Count);
}

For multiple character matches, which would correctly count the occurrences of "12", the Regex class comes in handy:

var query = list.Select(s => new
                {
                    Value = s,
                    Count = Regex.Matches(input, s).Count
                });
查看更多
手持菜刀,她持情操
6楼-- · 2019-04-11 00:16

I would try the following:

count = mylist.Count(s => myString.Contains(s));
查看更多
趁早两清
7楼-- · 2019-04-11 00:16

If myList is just List<string>, then this should work:

int count = myList.Count(x => myString.Contains(x));

If myList is List<List<string>>:

int count = myList.SelectMany(x => x).Count(s => myString.Contains(s));
查看更多
登录 后发表回答