我正在寻找一种搜索列表的方法,该列表根据我在该列表上进行的搜索返回一堆索引。对于ex,我有一个逗号分隔的字符串列表如下:
Blue, 3
Red, 3
Blue, 1
Blue, 9
Red, 5
我想进行搜索,返回所有元素的索引,除了包含在条件列表中找到的文本的任何元素。标准清单可以包含:
Blue, 3
Red, 5
所以在伪代码中,它会是,
ColorList.SelectIndex(!Containing(在criteriaList的所有元素中找到的单词)
上面应该返回索引1,2,3
由于
答案 0 :(得分:2)
var indexes = ColorList.Select((x, i) => new { Value = x, Index = i })
.Where(x => !criteriaList.Contains(x.Value))
.Select(x => x.Index);
如果您的列表包含许多项目,那么首先将criteriaList
转换为HashSet<T>
,可能可以获得更好的效果。 (您需要进行基准测试以确定在您的情况下这是否是更好的选择。)
var criteriaSet = new HashSet<string>(criteriaList);
var indexes = ColorList.Select((x, i) => new { Value = x, Index = i })
.Where(x => !criteriaSet.Contains(x.Value))
.Select(x => x.Index);
答案 1 :(得分:2)
var list = new []{"Blue, 3", "Red, 3", "Blue, 1", "Blue, 9", "Red, 5"};
var criteria = new []{"Blue, 3", "Red, 5"};
var filtered = list
.Select((s,i)=>new {s,i})
.Where(e => !criteria.Contains(e.s))
.Select(e => e.i);
结果:{ 1, 2, 3 }
答案 2 :(得分:2)
void Main()
{
var data = new List<string> {"Blue, 3", "Red, 3", "Blue, 1", "Blue, 9", "Red, 5"};
var colorList = new List<string> {"Blue, 3", "Red, 5"};
var indexes = data.Except(colorList).Select (x => data.IndexOf(x));
indexes.Dump();
}
答案 3 :(得分:0)
听起来你可能想要使用
List<KeyValuePair<string, int>> pair = new KeyValuePair<string, int>
然后你可以做
foreach (KeyValuePair<string, int> p in pair){
s = p.Key;
i = p.Value;
}
获取值
答案 4 :(得分:0)
我不太确定你想在这里实现什么,所以也许我的答案不是你想要的。
无论如何,在通用列表中,您可以在集合中使用lambda expression / linq语句。考虑一下我为你写的这些例子:
internal class ListLambdaLINQSample
{
List<KeyValuePair<Colors, int>> listSource;
List<KeyValuePair<Colors, int>> listCriteria;
List<KeyValuePair<Colors, int>> listMatches;
private const int COLORCODE1 = 1;
private const int COLORCODE2 = 2;
private const int COLORCODE3 = 3;
private const int COLORCODE4 = 4;
private const int COLORCODE5 = 5;
internal enum Colors
{
Red, Blue, Green, Yellow
}
public ListLambdaLINQSample()
{ // populate the list
listSource = new List<KeyValuePair<Colors, int>>();
listCriteria = new List<KeyValuePair<Colors, int>>();
_populateListCriteria();
_populateListSource();
...
}
private void _getMatchesWithLINQ()
{
listMatches =
(from kvpInList
in listSource
where !listCriteria.Contains(kvpInList)
select kvpInList).ToList();
}
private void _getMatchesWithLambda()
{
listMatches =
listSource.Where(kvpInList => !listCriteria.Contains(kvpInList)).ToList();
}
private void _populateListSource()
{
listSource.Add(new KeyValuePair<Colors, int>(Colors.Blue, COLORCODE1));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Green, COLORCODE2));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Red, COLORCODE3));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Yellow, COLORCODE4));
}
private void _populateListCriteria()
{
listCriteria.Add(new KeyValuePair<Colors, int>(Colors.Blue, COLORCODE1));
listCriteria.Add(new KeyValuePair<Colors, int>(Colors.Green, COLORCODE2));
}
}
希望这会有所帮助!!
此致 尼科
PS:我还没有编译或测试过这段代码。