比较基于一些(不是全部)属性值的列表内容的替代方法 [英] Alternatives to nested foreach when comparing list contents based on some (not all) property values

查看:118
本文介绍了比较基于一些(不是全部)属性值的列表内容的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为这个问题的一部分,我们反复指出我有一个O(n ^ 2)问题类似这样的代码...

pre $ $ $ $
$公共字符串IdentityValue {get; set ;}
public string Prop1 {get; set;}
public string Prop2 {get; set;}


$ b $ List< Foo> itemSet1 = GenerateLargeItemSet(); //制作一个大列表,> 5000件商品,例如
列表< Foo> itemSet2 = GenerateLargeItemSet();

foreach(itemSet1中的var itemFromSet1)
{

// itemSet2中是否存在相应的项目?
var itemSet2Item = itemSet2.FirstOrDefault(i => i.IdentityValue == itemFromSet1.IdentityValue);

if(itemSet2Item!= null)
{
//做东西来创建持久存储中的元素
}
else
{
//做些东西来更新持久存储中的项目


code $ $ $ $ $ $为了减少字符串比较和并行化的考虑,是否有一个便宜而通用的对象(对象可能是T类型,而Identity属性可能是其他的)来减少这个O(n ^ 2)的性质? p>

解决方案

其中一个解决方案是使用 Enumerable.Join 方法有复杂的 O(n)的

 列表< Foo> itemSet1 = GenerateLargeItemSet(); //制作一个大列表,> 5000件商品,例如
列表< Foo> itemSet2 = GenerateLargeItemSet();

// O(n)
var joinedSet = itemSet1.Join(itemSet2,s1 => s1.IdentityValue,s2 => s2.IdentityValue,(f1,f2)=> ; f1).ToList();

// O(n)
foreach(在joinedSet中的var joinedItem)
{
//在持久储存库中创建项目
}

// O(n)
var unjoinedSet = itemSet1.Except(joinedSet);

// O(n)
foreach(unjoinedSet中的unjoinedItem)
{
//执行更新持久存储区中的项目
}


As part of this question, it was pointed out repeatedly that I had an O(n^2) problem using code similar to this...

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 update item in the persistent store
  }
}

Excusing the string comparison and parallelization considerations, is there a cheap and generic (objects may be type T, and the Identity property may be something else) way to reduce the O(n^2) nature of this?

解决方案

One of solutions is to use Enumerable.Join method which have complextiy O(n)

List<Foo> itemSet1 = GenerateLargeItemSet(); //makes a large list, > 5000 items for example
List<Foo> itemSet2 = GenerateLargeItemSet();

// O(n)
var joinedSet = itemSet1.Join(itemSet2, s1 => s1.IdentityValue, s2 => s2.IdentityValue, (f1, f2) => f1).ToList();

// O(n)
foreach (var joinedItem in joinedSet)
{
    //do stuff to create item in the persistent store
}

// O(n)
var unjoinedSet = itemSet1.Except(joinedSet);

// O(n)
foreach (var unjoinedItem in unjoinedSet)
{
    //do stuff to update item in the persistent store
}

这篇关于比较基于一些(不是全部)属性值的列表内容的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆