Get all fixed drives names to a string array - c#

I want to get all the fixed drives names as a string array to give names for radio buttons..
this is the code i have used..
var drvs = System.IO.DriveInfo.GetDrives();
int hdcount = 0;
string[] drivenames;
foreach (var drv in drvs)
{
if (drv.DriveType == System.IO.DriveType.Fixed)
{
drivenames[hdcount] = drv.Name;
hdcount++;
}
}
But this code does not work.
it says "Error 1 Use of unassigned local variable 'drivenames'"
whats the wrong with my code ? how can i fix this ?

You have just declared the array string[] drivenames;, but you need to allocate the space required for the drive names, string[] drivenames = new string[fixedDriveCount]; but this is a bit unpractical because you should know the number of fixed drives before. Also there are more powerfull objects to store a collection of items that don't require to know the number of items to store in the collection before hand. I suggest to use a List<string> instead
var drvs = System.IO.DriveInfo.GetDrives();
List<string> drivenames = new List<string>();
foreach (var drv in drvs)
{
if (drv.DriveType == System.IO.DriveType.Fixed)
{
drivenames.Add(drv.Name);
}
}
int hdcount = drivenames.Count;
And with Linq you could shorten everything to
var drvs = DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.Fixed)
.Select(k => k.Name).ToList();
// and then use the result to initialize a listbox (for example)
listBox1.DataSource = drvs;

Here is how to do it Linqy
String []dArray = System.IO.DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.Fixed)
.Select(d => d.Name).ToArray();
or
List<string> dList = System.IO.DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.Fixed)
.Select(d => d.Name).ToList();

You missed to initialize your string array. You can do this by using the number of drives.
Try
var drvs = System.IO.DriveInfo.GetDrives();
int hdcount = 0;
string[] drivenames = new string[drvs.Count()];
foreach (var drv in drvs)
{
if (drv.DriveType == System.IO.DriveType.Fixed)
{
drivenames[hdcount] = drv.Name;
hdcount++;
}
}

Related

How can I convert IList<object> to string array?

How can I convert IList objects to string array?
While working on the telegram bot, some difficulties arose. I get a IList<object> from google table with some information. I need to convert this IList<object> to an array of strings. How can I do this?
static void ReadBudgetTypes()
{
var range = $"{settingsSheet}!B3:B";
var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
var response = request.Execute();
var values = response.Values; // here i get list of objects from google table
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
Console.WriteLine("{0}", row[0]);
}
}
else
{
Console.WriteLine("No data!");
}
}
Assuming cells may not be strings and may (or may not) have null values, you can print for each cell of the row:
// assumes ToString() gives a meaningful string
var listOfStrings = row.Select(x => x?.ToString()).ToList();
foreach(string cell in listOfStrings)
Console.WriteLine(cell);
or the whole row, joined by a separator
Console.WriteLine(string.Join(", ", row);
If you know the cells are strings you can just cast
var listOfStrings = row.Cast<string>().ToList();
// or
var listOfStrings = row.Select(x => (string)x).ToList();
and then repeat either of the above (loop or string.Join).
If items could be null,
var listOfStrings = row.Select(x => (x ?? (object)"").ToString()).ToList();
you can try this:
var tempList=List<string>();
string[] arrayList=null;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
tempList.Add(row[0]);
}
arrayList=tempList.ToArray();
}
Try something like this:
IList<object> list = new List<object>(){ "something", "something else" };
string[] array = list.Select(item => (String)item).ToArray();

Remove duplicate combination of numbers in C# from csv

I'm trying to remove the duplicate combination from a csv file.
I tried using Distinct but it seems to stay the same.
string path;
string newcsvpath = #"C:\Documents and Settings\MrGrimm\Desktop\clean.csv";
OpenFileDialog openfileDial = new OpenFileDialog();
if (openfileDial.ShowDialog() == DialogResult.OK)
{
path = openfileDial.FileName;
var lines = File.ReadLines(path);
var grouped = lines.GroupBy(line => string.Join(", ", line.Split(',').Distinct())).ToArray();
var unique = grouped.Select(g => g.First());
var buffer = new StringBuilder();
foreach (var name in unique)
{
string value = name;
buffer.AppendLine(value);
}
File.WriteAllText(newcsvpath ,buffer.ToString());
label5.Text = "Complete";
}
For example, I have a combination of
{ 1,1,1,1,1,1,1,1 } { 1,1,1,1,1,1,1,2 }
{ 2,1,1,1,1,1,1,1 } { 1,1,1,2,1,1,1,1 }
The output should be
{ 1,1,1,1,1,1,1,1 }
{ 2,1,1,1,1,1,1,1 }
From you example, it seems that you want to treat each line as a sequence of numbers and that you consider two lines equal if one sequence is a permutation of the other.
So from reading your file, you have:
var lines = new[]
{
"1,1,1,1,1,1,1,1",
"1,1,1,1,1,1,1,2",
"2,1,1,1,1,1,1,1",
"1,1,1,2,1,1,1,1"
};
Now let's convert it to an array of number sequences:
var linesAsNumberSequences = lines.Select(line => line.Split(',')
.Select(int.Parse)
.ToArray())
.ToArray();
Or better, since we are not interested in permutations, we can sort the numbers in the sequences immediately:
var linesAsSortedNumberSequences = lines.Select(line => line.Split(',')
.Select(int.Parse)
.OrderBy(number => number)
.ToArray())
.ToArray();
When using Distinct on this, we have to pass a comparer which considers two array equal, if they have the same elements. Let's use the one from this SO question
var result = linesAsSortedNumberSequences.Distinct(new IEnumerableComparer<int>());
Try it
HashSet<string> record = new HashSet<string>();
foreach (var row in dtCSV.Rows)
{
StringBuilder textEditor= new StringBuilder();
foreach (string col in columns)
{
textEditor.AppendFormat("[{0}={1}]", col, row[col].ToString());
}
if (!record.Add(textEditor.ToString())
{
}
}

Finding all identifiers containing part of the token

I know I can get a string from resources using
Resources.GetIdentifier(token, "string", ctx.ApplicationContext.PackageName)
(sorry, this is in C#, it's part of a Xamarin.Android project).
I know that if my elements are called foo_1, foo_2, foo_3, then I can iterate and grab the strings using something like
var myList = new List<string>();
for(var i = 0; i < 4; ++i)
{
var id = AppContent.GetIdentifier(token + i.ToString(), "string", "package_name");
if (id != 0)
myList.Add(AppContext.GetString(id));
}
My issue is that my token names all begin with "posn." (the posn can denote the position of anything, so you can have "posn.left_arm" and "posn.brokenose"). I want to be able to add to the list of posn elements, so I can't really store a list of the parts after the period. I can't use a string-array for this either (specific reason means I can't do this).
Is there a way that I can use something akin to "posn.*" in the getidentifer call to return the ids?
You can use some reflection foo to get what you want. It is not pretty at all but it works. The reflection stuff is based on https://gist.github.com/atsushieno/4e66da6e492dfb6c1dd0
private List<string> _stringNames;
private IEnumerable<int> GetIdentifiers(string contains)
{
if (_stringNames == null)
{
var eass = Assembly.GetExecutingAssembly();
Func<Assembly, Type> f = ass =>
ass.GetCustomAttributes(typeof(ResourceDesignerAttribute), true)
.OfType<ResourceDesignerAttribute>()
.Where(ca => ca.IsApplication)
.Select(ca => ass.GetType(ca.FullName))
.FirstOrDefault(ty => ty != null);
var t = f(eass) ??
AppDomain.CurrentDomain.GetAssemblies().Select(ass => f(ass)).FirstOrDefault(ty => ty != null);
if (t != null)
{
var strings = t.GetNestedTypes().FirstOrDefault(n => n.Name == "String");
if (strings != null)
{
var fields = strings.GetFields();
_stringNames = new List<string>();
foreach (var field in fields)
{
_stringNames.Add(field.Name);
}
}
}
}
if (_stringNames != null)
{
var names = _stringNames.Where(s => s.Contains(contains));
foreach (var name in names)
{
yield return Resources.GetIdentifier(name, "string", ComponentName.PackageName);
}
}
}
Then somewhere in your Activity you could do:
var ids = GetIdentifiers("action").ToList();
That will give you all the String Resources, which contain the string action.

Filtering a List with an array items

i need to filter a list with strings in an array. Below code doesn't return the expected result.
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
foreach (string item in subs)
{
obj = obj.Where(o => o.property.city.ToLower().Contains(item)).ToList();
}
As far as you're using Contains, I'd say you could be trying to get
entries, city of which matches any city from mystring
entries, city of which match all cities from mystring
So, having (I simplified searchModel class, having omitted property):
List<searchModel> obj = new List<searchModel>
{
new searchModel{city = "city1"},
new searchModel{city = "city2"},
new searchModel{city = "city3"}
};
var mystring = "city1,city2";
var subs = mystring.Split(',').ToList(); //let it be also List<T>
We can do:
//the 1st option
var orFilter = obj.Where(o => subs.Any(s => o.city.ToLower().Contains(s)))
.ToList();
//the 2nd option
var andFilter = obj.Where(o => subs.TrueForAll(s => o.city.ToLower().Contains(s)))
.ToList();
Then do a simple check
foreach (var o in andFilter)
{
Console.WriteLine(o.city);
}
I'd say that the OP is equal to option 2, not option 1.
I think you want this, or something close - I haven't tested it:
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
obj = obj.Where(o => subs.Contains(o.property.city.ToLower())).ToList();
What you're currently doing is filtering the list by ALL cities. So you'll only return results where o.property.city equals "city1" and "city2" (and any other cities you might have in the list). So you won't get any results.
To match any city in the list instead, try this:
var myFilteredObj = obj.Where(o => subs.Contains(o.property.city.ToLower()).ToList();
I add this codes of lines, probably will help someone and maybe someone will optimize it:
var jaggedArray = new string[100][];
var i = 0;
jaggedArray[i] = {"first folder","first file","first 5 files","last 5 folder"};
filter = "irs le";
var arrFilters = filter.Split(' ');
foreach (var arrFilter in arrFilters)
{
jaggedArray[i] = jaggedArray[i].Where(p =>p.ToLower().Contains(arrFilter.ToLower())).ToArray();
jaggedArray[i + 1] = jaggedArray[i];
i++;
}
return jaggedArray[i]; //new array after filter
//result: "first file","first 5 files"
var result = obj.Where(piD => subs.Contains(piD.city)).ToList();
The code above will filter the obj List based on the string array.

Change the foreach loop into the LINQ query

I stuck in an easy scenario. I have a List<string> object, all of its items has the body of:
item_1_2_generatedGUID //generatedGUID is Guid.NewGuid()
but there may be much more numbers
item_1_2_3_4_5_generatedGUID etc
now, I'm wondering how to change that loop into the LINQ's query. Any ideas ?
string one = "1"; //an exaplme
string two = "2"; //an exaplme
foreach (var item in myStringsList)
{
string[] splitted = item.Split(new char[] { '_' },
StringSplitOptions.RemoveEmptyEntries);
if(splitted.Length >= 3)
{
if(splitted[1] == one && splitted[2] == two)
{
resultList.Add(item);
}
}
}
var result = from s in lst
let spl = s.Split('_')
where spl.Length >= 3 && spl[1] = one && spl[2] == two
select s;
Try this:
var query = from item in myStringsList
let splitted = item.Split(new[] { '_' }, SSO.RemoveEmptyEntries)
where splitted.Length >= 3
where splitted[1] == one && splitted[2] == two
select item;
var resultList = query.ToList();
This is a different approach:
var items = myStringsList.
Where(x => x.Substring(x.IndexOf("_")).StartsWith(one+"_"+two+"_"));
You probably will need to add a +1 in the IndexOf, but I'm not sure.
What it does is:
Removes the first item (that's the substring for). In your example, it should be "1_2_3_4_5_generatedGUID"
Checks the string starts with what you are expecting. In your example: 1_2_
Edited: Added the pattern for anything at the first "position"
var result = items.Where(i => Regex.IsMatch(i, "^[^_]_1_2_"));

Categories