有没有更好的方法使用“Linq 样式”将列表插入/展开到列表中

本文关键字:列表 插入 样式 方法 更好 Linq 有没有 | 更新日期: 2023-09-27 17:56:57

我有一个字符串列表,在这个字符串列表中可能有对其他字符串列表的引用。 例如,假设列表如下所示:[a.txt, b.txt, c.more] ,当我迭代列表时,我想在字典中查找:{{'c.more', [c.txt, d.txt]}},以便由于在字典中查找c.more[a.txt, b.txt, c.txt, d.txt]结果列表。

我现在拥有的是这样的:

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。 现在我并不真正关心内存使用情况,但我觉得可能还有其他一些我还没有看到的方法来完成我所追求的事情。

有没有更好的方法来扩展包含更多列表的列表?

有没有更好的方法使用“Linq 样式”将列表插入/展开到列表中

你可能不再需要答案了,但我仍然想尝试一下。

一种选择是创建自己的类,从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();