A dumb C# question, if I have this code:
public class singleString
{
public string ss { get; set; }
}
List<singleString> manyString = new List<singleString>();
How can I populate manyString to something like {"1", "2", "3"} ?
You can do something like this:
List<singleString> manyString = new List<singleString>()
{
new singleString(){ss="1"},
new singleString(){ss="2"},
new singleString(){ss="3"},
};
Define implicit conversion operator
public class singleString {
public string ss { get; set; }
public static implicit operator singleString(string s) {
return new singleString { ss = s };
}
}
Then, use List initializer
var manyString = new List<singleString>() { "1", "2", "3" };
You can also initialize an array using the same operator
singleString[] manyString = { "1", "2", "3" };
Related
Here's what I've done so far
public enum TCountryNames
{
[Display(Name="America")]
cnUSA = 1,
[Display(Name="England")]
cnUK,
[Display(Name="CHINA")]
cnCHN
}
public class MyClass
{
public static List<KeyValuePair<string, int>> GetEnumList()
{
var list = new List<KeyValuePair<string, int>>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new KeyValuePair<string, int>(e.ToString(), (int)e));
}
return list;
}
}
Result: [cnUSA,1] with total count 3 and without header
The result i want is [{"Id":1,"Name":"America"},{"Id":2,"Name":"England"}]
I've tried [JsonConverter(typeof(StringEnumConverter))]
public TCountryNames Names{ get; set; }
I've also tried converting enum to array list var names = Enum.GetValues(typeof(TCountryNames));
ArrayList arrLst = new ArrayList() { names };
but both of them doesn't seems to be working.
*Any help will be appreciated. Thank You in Advance. *
If you don't want to add new class
public static List<Dictionary<string, object>> GetEnumList()
{
var list = new List<Dictionary<string, object>>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new Dictionary<string, object> { { "Id", (int)e }, { "Name", e.ToString() } });
}
return list;
}
Define a model for serialization
public class EnumData
{
public int Id { get; set; }
public string Name { get; set; }
}
public static List<EnumData> GetEnumList()
{
var list = new List<EnumData>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new EnumData { Id = (int)e, Name = e.ToString() });
}
return list;
}
For get display name value you should use System.Reflection. And then you could do this in simple way:
public enum TCountryNames
{
[Display(Name = "America")]
cnUSA = 1,
[Display(Name = "England")]
cnUK,
[Display(Name = "CHINA")]
cnCHN
}
public class EnumData
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class MyClass
{
public static List<EnumData> GetEnumList()
{
var list = new List<EnumData>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new EnumData
{
Id = (int)e,
Name = e.GetType()
.GetMember(e.ToString())
.First()?
.GetCustomAttribute<DisplayAttribute>()?
.GetName()
});
}
return list;
}
}
So to clarify:
you create loop foreach enum
take id by casting
take name using reflaction - I added all needed protection against null exception
Output:
[
{
"Id": 1,
"Name": "America"
},
{
"Id": 2,
"Name": "England"
},
{
"Id": 3,
"Name": "CHINA"
}
]
Example: https://dotnetfiddle.net/XVL2LI
Currently I have the following Json which I converted to plain object C# classes. My plain objects class I put them in a ModelMock class where I am trying to access the properties 'name' and 'value'. But I am unable to access and I get and error. The Error I am getting: 'List' does not contain a definition for 'name' and 'value'
Here is the Json for ref:
{
"matchActionsReasons": [
{
"name": "False positive",
"value": -2147483648
},
{
"name": "Acceptable risk",
"value": -2147483647
},
{
"name": "Manager approval",
"value": -2147483646
}
]
}
Here is my Model class:
public class ModelMock
{
public static ModelMock SaveSettingsModel()
{
return new ModelMock
{
matchActionsReasons =new List<MatchActionsReason>
{
name = "False positive", **//Geting the error here**
value = -2147483648 **//Geting the error here**
}
};
}
public class MatchActionsReason
{
public string name { get; set; }
public int value { get; set; }
}
public List<MatchActionsReason> matchActionsReasons { get; set; }
}
You must create and add objects of type MatchActionsReason:
// Using a collection initializer for the list
// and object initializers for the items
matchActionsReasons = new List<MatchActionsReason>{
new MatchActionsReason{ name = "False positive", value = -2147483648 },
new MatchActionsReason{ name = "Acceptable risk", value = -2147483647 },
new MatchActionsReason{ name = "Manager approval", value = -2147483646 }
};
or
// Using Add
matchActionsReasons = new List<MatchActionsReason>();
matchActionsReasons.Add(
new MatchActionsReason{ name = "False positive", value = -2147483648 }
);
matchActionsReasons.Add(
new MatchActionsReason{ name = "Acceptable risk", value = -2147483647 }
);
matchActionsReasons.Add(
new MatchActionsReason{ name = "Manager approval", value = -2147483646 }
);
The List<T> class itself does not have name and value properties. It has, among others, a Count property.
You can access member of elements of the list like this:
string s = matchActionsReasons[1].name; // ==> "Acceptable risk"
or
MatchActionsReason mar = matchActionsReasons[1];
string s = mar.name; // ==> "Acceptable risk"
You have to write it like this:
matchActionsReasons =new List<MatchActionsReason>
{
new MatchActionReason
{
name = "False positive",
value = -2147483648
},
add more instances here...
}
So the complete sample looks like this:
public class ModelMock
{
public static ModelMock SaveSettingsModel()
{
return new ModelMock
{
matchActionsReasons =new List<MatchActionsReason>
{
new MatchActionReason
{
name = "False positive",
value = -2147483648
},
new MatchActionReason
{
name = "Another False One",
value = -111111111
},
add more instances here...
}
};
}
public class MatchActionsReason
{
public string name { get; set; }
public int value { get; set; }
}
public List<MatchActionsReason> matchActionsReasons { get; set; }
}
The reason is that when you do new List { put here the new instances }
So in between the brackets you put the instances you are adding to the list.
That is called a collection initializer.
This is Microsoft's documentation for Obejct and Collection Initializers
You need to add a new MatchActionsReason object to your list. Like below.
matchActionsReasons = new List<MatchActionsReason>();
matchActionsReasons.Add(new MatchActionsReason(){ name = "foo", value = 115 });
This question already has answers here:
Determine if a sequence contains all elements of another sequence using Linq [duplicate]
(4 answers)
Closed 7 years ago.
Ok, so I have two elements:
class Full
{
public string FullId {get; set;}
public List<string> Tapes {get; set;}
}
and
class OptSet
{
public string SetId {get; set;}
public list<string> Tapes2 {get; set;}
}
I need to select a Full which list of Tapes contains all elements from OptSet list of Tapes2.
I need to do it in Linq. I've tried
Full currFull = inputFull.Where(f =>
f.Tapes.Contains(OptSet.Tapes2.ToString())).FirstOrDefault();
but this results in null.
Does this work?
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Full full = new Full()
{
FullId = "A",
Tapes = new List<string>() { "1", "2", "4" }
};
List<OptSet> optSet = new List<OptSet>() {
new OptSet() { SetId = "x", Tapes2 = new List<string>() {"1", "2", "3"}},
new OptSet() { SetId = "y", Tapes2 = new List<string>() {"1", "2", "4"}},
new OptSet() { SetId = "z", Tapes2 = new List<string>() {"1", "2", "3", "4"}}
};
List<OptSet> results = optSet.Where(x => full.Tapes.Where(y => !x.Tapes2.Contains(y)).Count() == 0).ToList();
}
}
public class Full
{
public string FullId { get; set; }
public List<string> Tapes { get; set; }
}
public class OptSet
{
public string SetId { get; set; }
public List<string> Tapes2 { get; set; }
}
}
i have two generic lists with a few properties to compare but i want that the key identifiers are dynamic by a List<string>.
So lets say we have the class:
class A
{
string Name { get; set; }
string Color1 { get; set; }
string Color2 { get; set; }
string Length { get; set; }
}
The user now can select from an user interface which properties of two lists of those objects need to overlap so that a correct pair is selected. This is stored in a List<string>. As example, if the list string contains "Name" and "Color1" there will be only objects returned where "Name" and "Color1" are overlapping.
I was trying to write a function, but unfortunately i'm not sure which collection i should cast the generic lists to and how do i apply the names of the properties on those? If the name of the "identificators" were always the same, it wouldn't be a problem with Linq/Lambda ;)
Thanks in advance
You need to use reflection for this. This works:
public class A
{
public string Name { get; set; }
public string Color1 { get; set; }
public string Color2 { get; set; }
public string Length { get; set; }
public static IEnumerable<A> Intersecting(IEnumerable<A> input, List<string> propertyNames)
{
if(input == null)
throw new ArgumentNullException("input must not be null ", "input");
if (!input.Any() || propertyNames.Count <= 1)
return input;
var properties = typeof(A).GetProperties();
var validNames = properties.Select(p => p.Name);
if (propertyNames.Except(validNames, StringComparer.InvariantCultureIgnoreCase).Any())
throw new ArgumentException("All properties must be one of these: " + string.Join(",", validNames), "propertyNames");
var props = from prop in properties
join name in validNames.Intersect(propertyNames, StringComparer.InvariantCultureIgnoreCase)
on prop.Name equals name
select prop;
var allIntersecting = input
.Select(a => new {
Object = a,
FirstVal = props.First().GetValue(a, null),
Rest = props.Skip(1).Select(p => p.GetValue(a, null)),
})
.Select(x => new {
x.Object, x.FirstVal, x.Rest,
UniqueValues = new HashSet<object>{ x.FirstVal }
})
.Where(x => x.Rest.All(v => !x.UniqueValues.Add(v)))
.Select(x => x.Object);
return allIntersecting;
}
}
Sample data:
var aList = new List<A> {
new A { Color1 = "Red", Length = "2", Name = "Red" }, new A { Color1 = "Blue", Length = "2", Name = "Blue" },
new A { Color1 = "Red", Length = "2", Name = "A3" }, new A { Color1 = "Blue", Length = "2", Name = "A3" },
new A { Color1 = "Red", Length = "3", Name = "Red" }, new A { Color1 = "Blue", Length = "2", Name = "A6" },
};
var intersecting = A.Intersecting(aList, new List<string> { "Color1", "Name" }).ToList();
I have the following object structure:
public class A
{
public string ID { get; set; }
public IList<B> Values { get; set; }
}
public class B
{
public string Code { get; set; }
public string DisplayName { get; set; }
}
public List<A> IDs;
I would like to use Linq to query B and return a single instance of A with the single element of B in values. Is that possible? I currently do this with a foreach but I am thinking Linq would be neater.
foreach (A a in IDs)
{
foreach (B b in a.Values)
{
if (b.Code == code)
{
return (new A()
{
ID = a.ID,
Values = new List<B>()
{
new B()
{
Code = b.Code,
DisplayName = b.DisplayName
}
}
});
}
}
}
Try this:
IDs.Where(a=>a.ID = id)
.Select(a => new A()
{
ID = a.ID,
Values = new List<B>()
{
new B()
{
Code = a.Values.First().Code,
DisplayName = a.Values.First().DisplayName
}
}
});
In LINQ with the query-syntax:
return (from a in IDs
from b in a.Values
where b.Code == code
select (new A
{
ID = a.ID, Values = new List<B>
{
new B
{
Code = b.Code,
DisplayName = b.DisplayName
}
}
})).FirstOrDefault();
Run the following in LinqPad (LinqPad.com)
void Main()
{
List<A> IDs= new List<A>() {
new A() { ID = "1", Values = new List<B>() {
new B { Code = "1", DisplayName = "1"},
new B { Code = "2", DisplayName = "2"},
new B { Code = "3", DisplayName = "3"} } },
new A() { ID = "4", Values = new List<B>() {
new B { Code = "4", DisplayName = "4"},
new B { Code = "5", DisplayName = "5"},
new B { Code = "6", DisplayName = "6"} } },
new A() { ID = "7", Values = new List<B>() {
new B { Code = "7", DisplayName = "7"},
new B { Code = "8", DisplayName = "8"},
new B { Code = "9", DisplayName = "9"} } }
};
A result = IDs.Where(a => a.Values.Any(b=> b.Code == "4")).FirstOrDefault();
result.Dump();
result = IDs.FirstOrDefault(a => a.Values.Any(b=> b.Code == "8"));
result.Dump();
}
// Define other methods and classes here
public class A
{
public string ID { get; set; }
public IList<B> Values { get; set; }
}
public class B
{
public string Code { get; set; }
public string DisplayName { get; set; }
}
You get this:
Prior edits follow:
With the edit to the question:
A result = IDs.Where(a => a.Values.Any(b=> b.Code == code)).FirstOrDefault();
Original answer below
The following will return the first A element where ID = id
A result = IDs.Where(a => a.ID == id).FirstOrDefault();
This makes it a list
List<A> result = IDs.Where(a => a.ID == id).FirstOrDefault().ToList();