作为这个问题的一部分,反复指出我使用类似于此的代码有一个O(n ^ 2)问题...
public class Foo
{
public string IdentityValue {get;set;}
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
List<Foo> itemSet1 = GenerateLargeItemSet(); //makes a large list, > 5000 items for example
List<Foo> itemSet2 = GenerateLargeItemSet();
foreach (var itemFromSet1 in itemSet1)
{
//does a corresponding item exist in itemSet2?
var itemSet2Item = itemSet2.FirstOrDefault(i => i.IdentityValue == itemFromSet1.IdentityValue);
if (itemSet2Item != null)
{
//do stuff to create item in the persistent store
}
else
{
//do stuff to …Run Code Online (Sandbox Code Playgroud) 你能告诉我哪一个列表连接方法更有效,为什么?还是性能相同?有没有其他方法来处理这种情况(基于字段属性加入2个列表)?
我的代码:
public List<CombinedDatabaseStructure> Combine1(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
List<CombinedDatabaseStructure> combinedAll = new List<CombinedDatabaseStructure>();
foreach (var row1 in _Data1)
{
foreach (var row2 in _Data2)
{
CombinedDatabaseStructure combined = new CombinedDatabaseStructure();
if (row1.ID == row2.ID)
{
combined.DatabaseStructure1 = row1;
combined.DatabaseStructure2 = row2;
combinedAll.Add(combined);
}
}
}
return combinedAll;
}
Run Code Online (Sandbox Code Playgroud)
代码2:
public List<CombinedDatabaseStructure> Combine2(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
var joined = from item1 in _Data1.AsEnumerable()
join item2 in _Data2.AsEnumerable() on item1.ID equals item2.ID
select new CombinedDatabaseStructure (item1,item2);
return joined.ToList<CombinedDatabaseStructure>();
}
Run Code Online (Sandbox Code Playgroud) 我想要一种在保持重复和顺序的同时对字符串进行分组的有效方法。像这样的东西
1100110002200 -> 101020
Run Code Online (Sandbox Code Playgroud)
我以前试过这个
_case.GroupBy(c => c).Select(g => g.Key)
Run Code Online (Sandbox Code Playgroud)
但我得到了 102
但这给了我我想要的,我只想优化它,所以我不必每次都搜索整个列表
static List<char> group(string _case)
{
var groups = new List<char>();
for (int i = 0; i < _case.Length; i++)
{
if (groups.LastOrDefault() != _case[i])
groups.Add(_case[i]);
}
return groups;
}
Run Code Online (Sandbox Code Playgroud) 我有一个对象列表,上面有一个名称字段.
我想知道是否有办法判断列表中的所有名称字段是否唯一.
我可以做两个循环并迭代列表中的每个值,但我想知道是否有更简洁的方法来使用LINQ做到这一点?
我找到了一些例子,他们将列表中的每个项目与硬编码值进行比较,但在我的情况下,我想比较每个对象之间的名称字段,并获得一个布尔值.
我有以下清单.
一个包含Person对象的列表具有Id&Name属性.People对象的其他列表具有Id,Name和Address属性.
List<Person> p1 = new List<Person>();
p1.Add(new Person() { Id = 1, Name = "a" });
p1.Add(new Person() { Id = 2, Name = "b" });
p1.Add(new Person() { Id = 3, Name = "c" });
p1.Add(new Person() { Id = 4, Name = "d" });
List<People> p2 = new List<People>();
p2.Add(new People() { Id = 1, Name = "a", Address=100 });
p2.Add(new People() { Id = 3, Name = "x", Address=101 });
p2.Add(new People() { Id = 4, …Run Code Online (Sandbox Code Playgroud)