int[] s1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] s2 = { 2, 2, 3, 3, 4, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 10, 10 };
var s3 = s1.ToList().Intersect(s2.ToList()).Select(p => "(" + p + "," + s2.ToList().Count(q => q == p) + ")").ToArray();
调试欢乐多
{
List<int> s1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> s2 = new List<int> { 2, 2, 3, 3, 4, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 10, 10 }; var q = from p in s2
where s1.Contains(p)
group p by p into g
select new { g.Key, CountNum = g.Count() }; foreach (var s in q)
{
Console.WriteLine(s.Key.ToString() + "," + s.CountNum);
} Console.Read();
}你建一个console程序,把这个赋值上去,看看运行结果
List<int> s1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> s2 = new List<int> { 2, 2, 3, 3, 4, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 10, 10 }; var a = s2.Where(s => s1.Contains(s)).GroupBy(s => s).ToDictionary<IGrouping<int, int>, string>(g => g.Key + "," + g.Count().ToString());
int[] 源 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 据 = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int[,]> 果 = new List<int[,]>();
int 计 = 源.Length - 1;
do
{
int 结 = 据.Count(a => a == 源[计]);
if (结 > 0)
果.Add(new int[,] { { 源[计], 结 } });
} while (--计 > 0);
其实就是使用了LINQ 查询,linq类似查询数据库一样,可以对内存数据进行查询。这是c#的一个特性。
没有必要看懂这种 linq 程序。编程序要避免过分炫技而煞费苦心把程序弄成诡异形式。写 linq 程序就应该像 #2 楼那样写清晰的代码,防止过度。
int num = 0;
for (int j = 0; j < s1.Length; j++)
{
for (int i = 0; i < s2.Length; i++)
{
if (s2[i] <= s1[j])
{
if (s2[i] == s1[j]) { num++; }
}
else { break; }
}
s3[j, 0] = s1[j]; s3[j, 1] = num;
num = 0;
}