1. 程式人生 > >DataTabe(DataRow)之間比較求交集、並集、差集

DataTabe(DataRow)之間比較求交集、並集、差集

  DataSet ds = new DataSet();
            ds.Locale = CultureInfo.InvariantCulture;
            FillDataSet(ds);

            DataTable contactTable = ds.Tables["Contact"];

            // Create two tables.
            IEnumerable<DataRow> query1 = from contact in contactTable.AsEnumerable()
                                          where contact.Field<string>("Title") == "Ms."
                                          select contact;

            IEnumerable<DataRow> query2 = from contact in contactTable.AsEnumerable()
                                          where contact.Field<string>("FirstName") == "Sandra"
                                          select contact;


            DataTable contacts1 = query1.CopyToDataTable();
            DataTable contacts2 = query2.CopyToDataTable();

            // Find the intersection of the two tables-----求交集用 Intersect/Union(並集)/Except(差集)
            var contacts = contacts1.AsEnumerable().Intersect(contacts2.AsEnumerable(),
                                                                DataRowComparer.Default);

            Console.WriteLine("Intersection of contacts tables");
            foreach (DataRow row in contacts)
            {
                Console.WriteLine("Id: {0} {1} {2} {3}",
                    row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
            }