-1

my table looks kinda like this

ID  Name Username
--  ---- ----
1   A    null
2   B    charmander
3   C    null
4   D    null

I want to select 2 random null values from column Username and replace both with pikachu.

Is there a way I can to this in C#?

Appreciate any help

Stefan
  • 16,235
  • 9
  • 55
  • 74
  • *Is there a way* - the answer is typically "yes". Could you make the question slightly more involved? Show us what you've done, how you access your database, what you're stuck with.. – Caius Jard Feb 16 '22 at 15:52
  • If your question amounts to "how to pick a random row from a SQL table?", see https://stackoverflow.com/a/3339298/224370 – Ian Mercer Feb 16 '22 at 15:55

2 Answers2

2
UPDATE tab
SET username = 'pikachu'
WHERE id IN (SELECT id
             FROM tab
             WHERE username IS NULL
             ORDER BY random()
             LIMIT 2);

Yes, there are ways to run an SQL statement from C#, for example using the Npgsql provider.

Laurenz Albe
  • 167,868
  • 16
  • 137
  • 184
0

Assume that your table name is MyData. We create an instance of Random method to generate a random number of the list then we gonna replace the matching number of the index to pikachu

So try this out:

var random = new Random();

var usernameList = _context.MyData.select (x=>x.Username).ToList();

int index = random.Next(usernameList.Count);

var newList = usernameList .Select(s => s.Replace(usernameList[index],"pikachu")).ToList();


})

I've not tested this on my device but i think the concept will work for you!

NOTE: you may need to take care of converting int->string if needed. Also, try repeat the process for getting the second random element.

Fadi Akkad
  • 296
  • 9