我有一个数组string [] country = {"IND", "RSA", "NZ", "AUS", "WI", "SL", "ENG", "BAN"};
我有一串downloadString = "The match between India (IND) and Australia (AUS) is into its exciting phase. South Africa (RSA) won the match against England (ENG) "
所以我试图找到字符串中存在哪些数组元素。我能够发现字符串中存在IND
,RSA
,AUS
和ENG
。但是,我无法根据它们在字符串中的出现顺序对其进行排序。所以现在我得到的输出是IND, RSA, AUS, ENG
而我真正需要的是IND, AUS, RSA, ENG
我怎样才能做到这一点?
最佳答案
您可以使用Linq查询(我将您的原始数组重命名为countries
)来简洁地做到这一点:
var result = countries.Select(country => new { country,
index = downloadString.IndexOf(country)})
.Where(pair => pair.index >= 0)
.OrderBy(pair => pair.index)
.Select(pair => pair.country)
.ToArray();
结果为
IND, AUS, RSA, ENG
。