文字列のリストがあります:
{"foo", "str1", "str2", ..., "bar", ..., "baz", ...}
"foo"
と の間の文字列のサブリストを取得する必要があり"bar"
ます"baz"
。
linqでこれを行うことは可能ですか?
EDIT
リストを2回調べずにメソッドが必要です。
var idxFoo = list.IndexOf("foo");
var idxBar = list.IndexOf("bar");
var idxBaz = list.IndexOf("baz");
var subList1 = list.Skip(idxFoo).Take(idxBar - idxFoo);
var subList2 = list.Skip(idxBar).Take(idxBaz - idxBar);
膨大なデータ リストを 1 回だけ繰り返したい場合は、次のようにします。
List<string> longDataList = new List<string> { "foo", "str1", "str2", "str1", "str2", "str1", "str2", "bar", "str1", "str2", "str1", "str2", "str1", "str2", "baz", "str1", "str2", "str1", "str2", "str1", "str2" };
List<string> splitters = new List<string> { "foo", "bar", "baz" };
Dictionary<string, List<string>> resultDict = new Dictionary<string, List<string>>();
List<string> currentList = null;
longDataList.ForEach(s =>
{
if (splitters.Contains(s))
{
if (resultDict.ContainsKey(s))
currentList = resultDict[s];
else
{
currentList = new List<string>();
resultDict.Add(s, currentList);
}
}
else
currentList.Add(s);
});
少なくとも少しの linq を使用しますが、膨大なデータ リストを 1 回だけ反復するトリックを実行します。