using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestLinq
{
public class Person
{
public int Id { set; get; }
public String name { set; get; }
public String Sex { set; get; }
public int Money { set; get; }
public Person(int id, String name, String sex,int money)
{
this.Id = id;
this.name = name;
this.Sex = sex;
this.Money = money;
}
public Person()
{
}
public override string ToString()
{
return Id + ":" + name + ":" + Sex;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestLinq
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
List<Person> pList1 = new List<Person>();
Person p = new Person(1, "wuping3", "nv",1);
pList1.Add(p);
p = new Person(2, "wuping4", "nv",2);
pList1.Add(p);
p = new Person(3, "wuping5", "nv",3);
pList1.Add(p);
p = new Person(4, "wuping6", "nan",4);
pList1.Add(p);
p = new Person(5, "wuping7", "nan",5);
pList1.Add(p);
p = new Person(6, "wuping8", "nan",6);
pList1.Add(p);
List<Person> pList2 = new List<Person>();
p = new Person(0, "wuping3", "nv",7);
pList2.Add(p);
p = new Person(0, "wuping4", "nv",1);
pList2.Add(p);
p = new Person(0, "wuping5", "nv",2);
pList2.Add(p);
var updateDb = from u in pList1
from t in pList2
where u.name == t.name && u.Sex == t.Sex
select new { ID = u.Id, t };
List<Person> updateDbByID = new List<Person>();
foreach (var item in updateDb)
{
item.t.Id = item.ID;
updateDbByID.Add(item.t);
string key = item.t.name + "&" + item.t.Sex;
if (!ht.Contains(key))
{
ht.Add(key, item.t.Money);
}
else
{
int oldMoney = (int)ht[key];
ht[key] = oldMoney > item.t.Money ? oldMoney : item.t.Money;
}
}
foreach (Person item in updateDbByID)
{
Console.WriteLine(item);
}
Console.WriteLine("===========*****************************===========");
List<Person> insertIntoDb = pList1.Where(pq => !pList2.Any(p2 => p2.Id == pq.Id)).ToList<Person>();
foreach (Person item in insertIntoDb)
{
Console.WriteLine(item);
string key = item.name + "&" + item.Sex;
if (!ht.Contains(key))
{
ht.Add(key, item.Money);
}
else
{
int oldMoney = (int)ht[key];
ht[key] = oldMoney > item.Money ? oldMoney : item.Money;
}
}
Console.WriteLine("========需要更新的ZZ_SUM==========");
foreach (string key in ht.Keys)
{
Console.WriteLine(key+":"+ht[key]);
}
String updateIntoDBString = getUpdateSql(updateDbByID);
Console.WriteLine(updateIntoDBString);
Console.Read();
}
static string getUpdateSql(List<Person> pList)
{
string sqlUpdateString = "select * from Person where id in (@Id)";
int[]array = pList.Select(p => p.Id).ToArray<int>();
String ids = string.Concat("'",string.Join("','", array),"'");
Console.WriteLine(ids.ToString());
return sqlUpdateString.Replace("@Id", ids);
}
}
}