我有一个字符串列表,在这个字符串列表中可能会引用其他字符串列表。例如,假设列表是这样的:[a.txt, b.txt, c.more]
,当我遍历列表时,我想在字典中查找:{{'c.more', [c.txt, d.txt]}}
,以便生成的列表为[a.txt, b.txt, c.txt, d.txt]
as在字典中查找c.more
的结果。
我现在所拥有的是这样的:
var dict = new Dictionary<string,List<string>>
{
{"c.more", new List<string> { "c.txt", "d.txt" } }
}
list.SelectMany(
f =>
f.EndsWith(".more")
? Expand(f)
: Include(f, dict))
Where Expand and Include do this:
public IEnumerable<string> Include(string f) { yield return f; }
public IEnumerable<string> Expand(string f, Dictionary<string,List<string>> dict) {
return dict.ContainsKey(f) ? dict[f] : new List<string>();
}
我可以简单地在三元组的前半部分返回一个new List<string> { f }
以及在后半部分进行查找的结果,但是我想稍后处理一个递归查找,所以我正在研究Expand。现在我并不是真的关心内存使用情况,但我觉得可能还有其他一些方法可以做我以前没看过的事情。
是否有更好的方法来扩展包含更多列表的列表?
答案 0 :(得分:1)
您可能不再需要答案,但我仍想尝试。
一个选项是创建自己的继承自IEnumerable
的类。请采取以下措施:
public class LookupList : IEnumerable<string>
{
private readonly IEnumerable<string> _source;
private Dictionary<string, List<string>> _referenceDic;
public LookupList(IEnumerable<string> source, Dictionary<string, List<string>> referenceDic)
{
_source = source;
_referenceDic = referenceDic;
}
public IEnumerator<string> GetEnumerator()
{
foreach (string item in _source)
{
//check if it's in the ref dictionary, if yes: return only sub items, if no: return the item
if (_referenceDic.Keys.Contains(item))
{
foreach (string dicItem in _referenceDic[item])
yield return dicItem;
}
else
{
yield return item;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
现在运行以下行来访问这些项目。
Dictionary<string, List<string>> refData = new Dictionary<string, List<string>>();
LookupList lst = new LookupList(new List<string>() { "a.txt", "b.txt", "c.more" }, refData);
refData.Add("c.more", new List<string>() { "c.txt", "d.txt" });
List<string> flattenedItems = lst.ToList();