我有一段代码,可以将由 string, string, string
组成的类列表中某个属性的字符串拆分。
现在,我声明了一个空的 Dataframe2 (string,string[], string
) 并使用 Add
方法将项目添加到列表中。
class Program
{
public static string[] SPString(string text)
{
string[] elements;
elements = text.Split(' ');
return elements;
}
//Structures
public class Dataframe
{
public string Name { get; set; }
public string Text { get; set; }
public string Cat { get; set; }
}
public class Dataframe2
{
public string Name { get; set; }
public string[] Text { get; set; }
public string Cat { get; set; }
}
static void Main(string[] args)
{
List<Dataframe> doc = new List<Dataframe>{new Dataframe { Name = "Doc1", Text = "The quick brown cat", Cat = ""},
new Dataframe { Name = "Doc2", Text = "The big fat cat", Cat = "Two"},
new Dataframe { Name = "Doc4", Text = "The quick brown rat", Cat = "One"},
new Dataframe { Name = "Doc3", Text = "Its the cat in the hat", Cat = "Two"},
new Dataframe { Name = "Doc5", Text = "Mice and rats eat seeds", Cat = "One"},
};
// Can this be made more efficient?
ConcurrentBag<Dataframe2> doc2 = new ConcurrentBag<Dataframe2>();
Parallel.ForEach(doc, entry =>
{
string s = entry.Text;
string[] splitter = SPString(s);
doc2.Add(new Dataframe2 {Name = entry.Name, Text = splitter, Cat =entry.Cat});
} );
}
}
有没有更有效的方法使用并行LINQ向列表中添加内容,其中Dataframe2继承了我没有修改的属性?
List<T>
,它会产生意想不到的结果。请改用ConcurrentBag<T>
。 - Patrick Hofmandoc2.Add(new Dataframe2 {Name = entry.Name, Text = splitter, Cat =entry.Cat});
之外,是否有更高效的方法将东西添加到list<T>
中,比如应用一个掩码或映射我不使用的东西之类的。同时也不是很熟悉ConcurrentBag
,但我假设它是一个线程安全的列表? - ccsvList<T>
不是。 - Patrick Hofman