0

I've an object that is include property ID with values between 101 and 199. How to order it like 199,101,102 ... 198?

In result I want to put last item to first.


Rails import from csv to model

I have a csv file with dump data of table and I would like to import it directly into my database using rails.

I am currently having this code:

csv_text = File.read("public/csv_fetch/#{model.table_name}.csv")
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{model.table_name}")
puts "\nUpdating table #{model.table_name}"
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  row = row.to_hash.with_indifferent_access
  ActiveRecord::Base.record_timestamps = false
  model.create!(row.to_hash.symbolize_keys)
end

with help from here..

Consider my Sample csv:

id,code,created_at,updated_at,hashcode
10,00001,2012-04-12 06:07:26,2012-04-12 06:07:26,
2,00002,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
13,00007,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
43,00011,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
5,00012,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode

But problem with this code is :

  • It is generating `id' as autoincrement 1,2,3,.. instead of what in csv file.
  • The timestamps for records where there is 0000-00-00 00:00:00 defaults to null automatically and throws error as the column created_at cannot be null...

Is there any way I can do it in generic way to import from csv to models? or would i have to write custom code for each model to manipulate the attributes in each row manually??

4

7 に答える 7

7

The desired ordering makes no sense (some reasoning would be helpful), but this should do the trick:

int maxID = items.Max(x => x.ID); // If you want the Last item instead of the one
                                  // with the greatest ID, you can use
                                  // items.Last().ID instead.
var strangelyOrderedItems = items
    .OrderBy(x => x.ID == maxID ? 0 : 1)
    .ThenBy(x => x.ID);
于 2012-04-12T10:47:40.790 に答える
1

Depending whether you are interested in the largest item in the list, or the last item in the list:

internal sealed class Object : IComparable<Object>
{
   private readonly int mID; 
   public int ID { get { return mID; } }
   public Object(int pID) { mID = pID; }

   public static implicit operator int(Object pObject) { return pObject.mID; }
   public static implicit operator Object(int pInt) { return new Object(pInt); }

   public int CompareTo(Object pOther) { return mID - pOther.mID; }
   public override string ToString() { return string.Format("{0}", mID); }
}


List<Object> myList = new List<Object> { 1, 2, 6, 5, 4, 3 };

// the last item first
List<Object> last = new List<Object> { myList.Last() };
List<Object> lastFirst = 
   last.Concat(myList.Except(last).OrderBy(x => x)).ToList();

lastFirst.ForEach(Console.Write);
Console.WriteLine();
// outputs: 312456     

// or

// the largest item first
List<Object> max = new List<Object> { myList.Max() };
List<Object> maxFirst = 
   max.Concat(myList.Except(max).OrderBy(x => x)).ToList();

maxFirst.ForEach(Console.Write);
Console.WriteLine();
// outputs: 612345
于 2012-04-12T11:14:24.530 に答える
0

編集:最初に最後のアイテムが欲しいという部分を見逃しました。あなたはこのようにそれを行うことができます:

var objectList = new List<DataObject>();
var lastob = objectList.Last();
objectList.Remove(lastob);
var newList = new List<DataObject>();
newList.Add(lastob);
newList.AddRange(objectList.OrderBy(o => o.Id).ToList());

通常の並べ替えについて話している場合は、次のような方法でlinqの順序を使用できます。
objectList = objectList.OrderBy(ob => ob.ID).ToList();

于 2012-04-12T10:45:15.757 に答える
0

In result I want to put last item to first

first sort the list

List<int> values = new List<int>{100, 56, 89..}; 
var result = values.OrderBy(x=>x);

add an extension method for swaping an elements in the List<T>

static void Swap<T>(this List<T> list, int index1, int index2)
{
     T temp = list[index1];
     list[index1] = list[index2];
     list[index2] = temp;
}

after use it

result .Swap(0, result.Count -1);
于 2012-04-12T10:48:33.910 に答える
0

You can acheive this using a single Linq statment.

var ordering = testData
    .OrderByDescending(t => t.Id)
    .Take(1)
    .Union(testData.OrderBy(t => t.Id).Take(testData.Count() - 1));

Order it in reverse direction and take the top 1, then order it the "right way round" and take all but the last and union these together. There are quite a few variants of this approach, but the above should work.

This approach should work for arbitrary lists too, without the need to know the max number.

于 2012-04-12T10:51:44.500 に答える
0

How about

var orderedItems = items.OrderBy(x => x.Id)
var orderedItemsLastFirst = 
    orderedItems.Reverse().Take(1).Concat(orderedItems.Skip(1));

This will iterate the list several times so perhaps could be more efficient but doesn't use much code.

If more speed is important you could write a specialised IEnumerable extension that would allow you to sort and return without converting to an intermediate IEnumerable.

于 2012-04-12T11:00:21.813 に答える
-3
var myList = new List<MyObject>();
//initialize the list
var ordered = myList.OrderBy(c => c.Id); //or use OrderByDescending if you want reverse order
于 2012-04-12T10:49:09.493 に答える